feat: complete requirements gaps - backup/restore, uat signoff, pm attachments, templates, and filters
This commit is contained in:
@@ -2,9 +2,12 @@ backend/data/ams.db
|
|||||||
backend/data/test.db
|
backend/data/test.db
|
||||||
backend/data/uploads/*
|
backend/data/uploads/*
|
||||||
!backend/data/uploads/.gitkeep
|
!backend/data/uploads/.gitkeep
|
||||||
|
backend/data/backups/*
|
||||||
|
!backend/data/backups/.gitkeep
|
||||||
backend/data/*
|
backend/data/*
|
||||||
!backend/data/.gitkeep
|
!backend/data/.gitkeep
|
||||||
!backend/data/uploads/
|
!backend/data/uploads/
|
||||||
|
!backend/data/backups/
|
||||||
.venv/
|
.venv/
|
||||||
backend/.venv/
|
backend/.venv/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
|
|||||||
@@ -71,7 +71,51 @@ docker compose up --build
|
|||||||
|
|
||||||
## Documentation & Walkthroughs
|
## Documentation & Walkthroughs
|
||||||
- [10-Minute Demo Script](docs/DEMO_SCRIPT.md)
|
- [10-Minute Demo Script](docs/DEMO_SCRIPT.md)
|
||||||
- [Acceptance Checklist (Proposal §10)](docs/ACCEPTANCE_CHECKLIST.md)
|
- [Acceptance Checklist & UAT Sign-off Matrix](docs/ACCEPTANCE_CHECKLIST.md)
|
||||||
|
- [Role-Based User Guide](docs/USER_GUIDE.md)
|
||||||
|
- [Assumptions, Retention & Governance Policies](docs/ASSUMPTIONS.md)
|
||||||
|
|
||||||
|
## Database Backup & Disaster Recovery
|
||||||
|
|
||||||
|
The application includes an automated, online backup utility in `backend/scripts/backup.py` that utilizes SQLite's safe online backup API (`sqlite3.Connection.backup`) to capture a transactionally consistent snapshot of the database alongside all uploaded attachment files without requiring downtime.
|
||||||
|
|
||||||
|
### Running a Manual Backup
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
# Windows:
|
||||||
|
.venv\Scripts\python.exe scripts/backup.py backup
|
||||||
|
# macOS/Linux:
|
||||||
|
python scripts/backup.py backup
|
||||||
|
```
|
||||||
|
- Creates a timestamped archive: `backend/data/backups/ams_backup_YYYYMMDD_HHMMSS.zip` containing `ams.db` and the `uploads/` folder.
|
||||||
|
- Runs `PRAGMA integrity_check` automatically before bundling.
|
||||||
|
- Retains the latest 7 backups by default (`--keep N` flag configurable).
|
||||||
|
|
||||||
|
### Verifying Backup Integrity
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
python scripts/backup.py verify data/backups/ams_backup_20261113_174700.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
### Restoring from a Backup
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
python scripts/backup.py restore data/backups/ams_backup_YYYYMMDD_HHMMSS.zip
|
||||||
|
```
|
||||||
|
- Validates SQLite integrity before restoring.
|
||||||
|
- Automatically saves a `.safety_pre_restore_<timestamp>.bak` of the active database before overwriting.
|
||||||
|
- Unpacks attachments directly into `backend/data/uploads/`.
|
||||||
|
|
||||||
|
### Automated Nightly Backups
|
||||||
|
To schedule automatic nightly backups at 01:00 AM:
|
||||||
|
- **Linux / Docker (cron):**
|
||||||
|
```cron
|
||||||
|
0 1 * * * cd /path/to/poona-ams/backend && /path/to/poona-ams/backend/.venv/bin/python scripts/backup.py backup >> /var/log/ams_backup.log 2>&1
|
||||||
|
```
|
||||||
|
- **Windows (Task Scheduler / PowerShell):**
|
||||||
|
```powershell
|
||||||
|
schtasks /create /tn "PoonaAMS_NightlyBackup" /tr "powershell -ExecutionPolicy Bypass -Command 'cd C:\path\to\poona-ams\backend; .\.venv\Scripts\python.exe scripts\backup.py backup'" /sc daily /st 01:00
|
||||||
|
```
|
||||||
|
|
||||||
## Demo Accounts
|
## Demo Accounts
|
||||||
| Email | Password | Role |
|
| Email | Password | Role |
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class Complaint(Base):
|
|||||||
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
|
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
|
||||||
|
assigned_team: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||||
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ class DemoEquipment(Base):
|
|||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
serial_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
|
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
|
||||||
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
|
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
|
||||||
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
|
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
|
||||||
@@ -52,6 +53,7 @@ class DepartmentVisit(Base):
|
|||||||
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
||||||
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
new_requirements: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
||||||
|
|||||||
@@ -371,6 +371,8 @@ def list_assets(
|
|||||||
supplier_id: Optional[int] = None,
|
supplier_id: Optional[int] = None,
|
||||||
status_filter: Optional[str] = Query(None, alias="status"),
|
status_filter: Optional[str] = Query(None, alias="status"),
|
||||||
criticality: Optional[str] = None,
|
criticality: Optional[str] = None,
|
||||||
|
requires_calibration: Optional[bool] = None,
|
||||||
|
insurance_applicable: Optional[bool] = None,
|
||||||
warranty_status: Optional[str] = None,
|
warranty_status: Optional[str] = None,
|
||||||
contract_status: Optional[str] = None,
|
contract_status: Optional[str] = None,
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
@@ -401,6 +403,10 @@ def list_assets(
|
|||||||
query = query.filter(Asset.status == status_filter)
|
query = query.filter(Asset.status == status_filter)
|
||||||
if criticality:
|
if criticality:
|
||||||
query = query.filter(Asset.criticality == criticality)
|
query = query.filter(Asset.criticality == criticality)
|
||||||
|
if requires_calibration is not None:
|
||||||
|
query = query.filter(Asset.requires_calibration.is_(requires_calibration))
|
||||||
|
if insurance_applicable is not None:
|
||||||
|
query = query.filter(Asset.insurance_applicable.is_(insurance_applicable))
|
||||||
|
|
||||||
if q and q.strip():
|
if q and q.strip():
|
||||||
like = f"%{q.strip()}%"
|
like = f"%{q.strip()}%"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
@@ -25,6 +26,7 @@ from ..schemas.calibration import (
|
|||||||
CalibrationStatusFilter,
|
CalibrationStatusFilter,
|
||||||
)
|
)
|
||||||
from ..services.audit import log_audit
|
from ..services.audit import log_audit
|
||||||
|
from ..services.bulk_templates import build_calibration_template_xlsx
|
||||||
from ..services.calculations import compute_schedule_status
|
from ..services.calculations import compute_schedule_status
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
from ..services.settings_service import get_setting_value
|
from ..services.settings_service import get_setting_value
|
||||||
@@ -196,6 +198,19 @@ def _create_plan_and_initial_record(
|
|||||||
return plan
|
return plan
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/import-template")
|
||||||
|
def download_calibration_import_template(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
buf = build_calibration_template_xlsx(db)
|
||||||
|
return StreamingResponse(
|
||||||
|
buf,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": 'attachment; filename="calibration_import_template.xlsx"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/plans", response_model=CalibrationPlanListOut)
|
@router.get("/plans", response_model=CalibrationPlanListOut)
|
||||||
def list_calibration_plans(
|
def list_calibration_plans(
|
||||||
q: str = "",
|
q: str = "",
|
||||||
|
|||||||
@@ -144,6 +144,7 @@ def _to_complaint_out(
|
|||||||
received_at=recv_at,
|
received_at=recv_at,
|
||||||
assigned_to_id=c.assigned_to_id,
|
assigned_to_id=c.assigned_to_id,
|
||||||
assigned_to_name=user_names.get(c.assigned_to_id) if c.assigned_to_id else None,
|
assigned_to_name=user_names.get(c.assigned_to_id) if c.assigned_to_id else None,
|
||||||
|
assigned_team=c.assigned_team,
|
||||||
assigned_at=asg_at,
|
assigned_at=asg_at,
|
||||||
attended_by_id=c.attended_by_id,
|
attended_by_id=c.attended_by_id,
|
||||||
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
|
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
|
||||||
@@ -233,6 +234,7 @@ def _sync_asset_status(db: Session, asset: Asset, exclude_complaint_id: int, req
|
|||||||
def list_complaints(
|
def list_complaints(
|
||||||
q: Optional[str] = None,
|
q: Optional[str] = None,
|
||||||
department_id: Optional[int] = None,
|
department_id: Optional[int] = None,
|
||||||
|
location_id: Optional[int] = None,
|
||||||
asset_id: Optional[int] = None,
|
asset_id: Optional[int] = None,
|
||||||
call_status: Optional[str] = None,
|
call_status: Optional[str] = None,
|
||||||
priority: Optional[str] = None,
|
priority: Optional[str] = None,
|
||||||
@@ -260,6 +262,9 @@ def list_complaints(
|
|||||||
elif department_id is not None:
|
elif department_id is not None:
|
||||||
query = query.filter(Asset.department_id == department_id)
|
query = query.filter(Asset.department_id == department_id)
|
||||||
|
|
||||||
|
if location_id is not None:
|
||||||
|
query = query.filter(Asset.location_id == location_id)
|
||||||
|
|
||||||
if asset_id is not None:
|
if asset_id is not None:
|
||||||
query = query.filter(Complaint.asset_id == asset_id)
|
query = query.filter(Complaint.asset_id == asset_id)
|
||||||
if call_status:
|
if call_status:
|
||||||
@@ -372,6 +377,7 @@ def create_complaint(
|
|||||||
breakdown_details=payload.breakdown_details,
|
breakdown_details=payload.breakdown_details,
|
||||||
priority=payload.priority,
|
priority=payload.priority,
|
||||||
notes=payload.notes,
|
notes=payload.notes,
|
||||||
|
assigned_team=payload.assigned_team,
|
||||||
registered_at=reg_at,
|
registered_at=reg_at,
|
||||||
registered_by_id=current_user.id,
|
registered_by_id=current_user.id,
|
||||||
received_by_id=recv_by_id,
|
received_by_id=recv_by_id,
|
||||||
@@ -555,19 +561,34 @@ def assign_complaint(
|
|||||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||||
):
|
):
|
||||||
comp = _load_complaint_or_404(db, complaint_id)
|
comp = _load_complaint_or_404(db, complaint_id)
|
||||||
|
if payload.assigned_to_id is None and not payload.assigned_team:
|
||||||
|
raise HTTPException(status_code=422, detail="Either assigned_to_id or assigned_team must be provided.")
|
||||||
|
|
||||||
|
assignee: Optional[User] = None
|
||||||
|
target_name = payload.assigned_team or ""
|
||||||
|
if payload.assigned_to_id is not None:
|
||||||
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
|
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
|
||||||
if assignee is None:
|
if assignee is None:
|
||||||
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
|
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
|
||||||
|
target_name = assignee.name
|
||||||
|
if payload.assigned_team:
|
||||||
|
target_name = f"{assignee.name} ({payload.assigned_team})"
|
||||||
|
|
||||||
old_name: Optional[str] = None
|
old_name: Optional[str] = None
|
||||||
event_type = "assigned"
|
event_type = "assigned"
|
||||||
if comp.assigned_to_id is not None:
|
if comp.assigned_to_id is not None or comp.assigned_team:
|
||||||
event_type = "reassigned"
|
event_type = "reassigned"
|
||||||
|
if comp.assigned_to_id is not None:
|
||||||
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
|
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
|
||||||
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
|
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
|
||||||
|
if comp.assigned_team:
|
||||||
|
old_name = f"{old_name} ({comp.assigned_team})" if old_name else comp.assigned_team
|
||||||
|
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
|
if assignee:
|
||||||
comp.assigned_to_id = assignee.id
|
comp.assigned_to_id = assignee.id
|
||||||
|
if payload.assigned_team is not None:
|
||||||
|
comp.assigned_team = payload.assigned_team.strip() or None
|
||||||
comp.assigned_at = now
|
comp.assigned_at = now
|
||||||
if comp.call_status == "open":
|
if comp.call_status == "open":
|
||||||
comp.call_status = "in_progress"
|
comp.call_status = "in_progress"
|
||||||
@@ -578,7 +599,7 @@ def assign_complaint(
|
|||||||
complaint_id=comp.id,
|
complaint_id=comp.id,
|
||||||
event_type=event_type,
|
event_type=event_type,
|
||||||
from_value=old_name,
|
from_value=old_name,
|
||||||
to_value=assignee.name,
|
to_value=target_name,
|
||||||
by_user_id=current_user.id,
|
by_user_id=current_user.id,
|
||||||
at=now,
|
at=now,
|
||||||
note=payload.note,
|
note=payload.note,
|
||||||
@@ -589,7 +610,11 @@ def assign_complaint(
|
|||||||
entity_type="complaint",
|
entity_type="complaint",
|
||||||
entity_id=comp.id,
|
entity_id=comp.id,
|
||||||
action=event_type,
|
action=event_type,
|
||||||
changes={"assigned_to_id": assignee.id, "note": payload.note},
|
changes={
|
||||||
|
"assigned_to_id": comp.assigned_to_id,
|
||||||
|
"assigned_team": comp.assigned_team,
|
||||||
|
"note": payload.note,
|
||||||
|
},
|
||||||
user_id=current_user.id,
|
user_id=current_user.id,
|
||||||
)
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
@@ -21,6 +22,7 @@ from ..schemas.contracts import (
|
|||||||
)
|
)
|
||||||
from ..services.attachment_service import get_attachment_counts
|
from ..services.attachment_service import get_attachment_counts
|
||||||
from ..services.audit import log_audit
|
from ..services.audit import log_audit
|
||||||
|
from ..services.bulk_templates import build_contracts_template_xlsx
|
||||||
from ..services.calculations import coverage_status
|
from ..services.calculations import coverage_status
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
from ..services.settings_service import get_setting_value
|
from ..services.settings_service import get_setting_value
|
||||||
@@ -187,6 +189,19 @@ def get_contract_history(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/import-template")
|
||||||
|
def download_contracts_import_template(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
buf = build_contracts_template_xlsx(db)
|
||||||
|
return StreamingResponse(
|
||||||
|
buf,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": 'attachment; filename="contracts_import_template.xlsx"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
||||||
def create_contract(
|
def create_contract(
|
||||||
payload: ContractCreate,
|
payload: ContractCreate,
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ def _to_demo_out(
|
|||||||
id=item.id,
|
id=item.id,
|
||||||
name=item.name,
|
name=item.name,
|
||||||
equipment_type=item.equipment_type,
|
equipment_type=item.equipment_type,
|
||||||
|
serial_no=item.serial_no,
|
||||||
supplier_id=item.supplier_id,
|
supplier_id=item.supplier_id,
|
||||||
supplier_name=item.supplier.name if item.supplier else None,
|
supplier_name=item.supplier.name if item.supplier else None,
|
||||||
department_id=item.department_id,
|
department_id=item.department_id,
|
||||||
@@ -160,6 +161,7 @@ def create_demo_equipment(
|
|||||||
item = DemoEquipment(
|
item = DemoEquipment(
|
||||||
name=payload.name.strip(),
|
name=payload.name.strip(),
|
||||||
equipment_type=payload.equipment_type.strip(),
|
equipment_type=payload.equipment_type.strip(),
|
||||||
|
serial_no=payload.serial_no.strip() if payload.serial_no else None,
|
||||||
supplier_id=payload.supplier_id,
|
supplier_id=payload.supplier_id,
|
||||||
department_id=payload.department_id,
|
department_id=payload.department_id,
|
||||||
location_id=payload.location_id,
|
location_id=payload.location_id,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
@@ -17,6 +18,7 @@ from ..schemas.insurance import (
|
|||||||
)
|
)
|
||||||
from ..services.attachment_service import get_attachment_counts
|
from ..services.attachment_service import get_attachment_counts
|
||||||
from ..services.audit import log_audit
|
from ..services.audit import log_audit
|
||||||
|
from ..services.bulk_templates import build_insurance_template_xlsx
|
||||||
from ..services.calculations import coverage_status
|
from ..services.calculations import coverage_status
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
from ..services.settings_service import get_setting_value
|
from ..services.settings_service import get_setting_value
|
||||||
@@ -136,6 +138,19 @@ def list_insurance_policies(
|
|||||||
return InsuranceListOut(items=items_all[start : start + page_size], total=total)
|
return InsuranceListOut(items=items_all[start : start + page_size], total=total)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/import-template")
|
||||||
|
def download_insurance_import_template(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
buf = build_insurance_template_xlsx(db)
|
||||||
|
return StreamingResponse(
|
||||||
|
buf,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": 'attachment; filename="insurance_import_template.xlsx"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
|
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
|
||||||
def create_insurance_policy(
|
def create_insurance_policy(
|
||||||
payload: InsuranceCreate,
|
payload: InsuranceCreate,
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ def _to_visit_out(v: DepartmentVisit) -> VisitOut:
|
|||||||
visited_by_name=v.visited_by.name if v.visited_by else None,
|
visited_by_name=v.visited_by.name if v.visited_by else None,
|
||||||
visit_date=v.visit_date,
|
visit_date=v.visit_date,
|
||||||
observations=v.observations,
|
observations=v.observations,
|
||||||
|
new_requirements=v.new_requirements,
|
||||||
assets=[
|
assets=[
|
||||||
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
|
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
|
||||||
for a in v.assets
|
for a in v.assets
|
||||||
@@ -198,6 +199,7 @@ def create_visit(
|
|||||||
visited_by_id=visited_by_id,
|
visited_by_id=visited_by_id,
|
||||||
visit_date=payload.visit_date,
|
visit_date=payload.visit_date,
|
||||||
observations=clean_obs,
|
observations=clean_obs,
|
||||||
|
new_requirements=payload.new_requirements.strip() if payload.new_requirements else None,
|
||||||
created_by_id=current_user.id,
|
created_by_id=current_user.id,
|
||||||
updated_by_id=current_user.id,
|
updated_by_id=current_user.id,
|
||||||
)
|
)
|
||||||
@@ -254,6 +256,9 @@ def update_visit(
|
|||||||
detail="observations cannot be blank.",
|
detail="observations cannot be blank.",
|
||||||
)
|
)
|
||||||
visit.observations = clean_obs
|
visit.observations = clean_obs
|
||||||
|
if "new_requirements" in data:
|
||||||
|
req = data["new_requirements"]
|
||||||
|
visit.new_requirements = req.strip() if isinstance(req, str) and req.strip() else None
|
||||||
|
|
||||||
assets_list, complaints_list = _resolve_assets_and_complaints(
|
assets_list, complaints_list = _resolve_assets_and_complaints(
|
||||||
db,
|
db,
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ class ComplaintCreate(BaseModel):
|
|||||||
breakdown_details: Optional[str] = None
|
breakdown_details: Optional[str] = None
|
||||||
priority: ComplaintPriority = "non_critical"
|
priority: ComplaintPriority = "non_critical"
|
||||||
notes: Optional[str] = None
|
notes: Optional[str] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
received_by_id: Optional[int] = None
|
received_by_id: Optional[int] = None
|
||||||
received_at: Optional[datetime] = None
|
received_at: Optional[datetime] = None
|
||||||
|
|
||||||
@@ -28,6 +29,7 @@ class ComplaintUpdate(BaseModel):
|
|||||||
breakdown_details: Optional[str] = None
|
breakdown_details: Optional[str] = None
|
||||||
priority: Optional[ComplaintPriority] = None
|
priority: Optional[ComplaintPriority] = None
|
||||||
notes: Optional[str] = None
|
notes: Optional[str] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
closure_remarks: Optional[str] = None
|
closure_remarks: Optional[str] = None
|
||||||
# Restricted technical fields (system_admin / biomedical only)
|
# Restricted technical fields (system_admin / biomedical only)
|
||||||
action_taken: Optional[str] = None
|
action_taken: Optional[str] = None
|
||||||
@@ -43,7 +45,8 @@ class ComplaintUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ComplaintAssignIn(BaseModel):
|
class ComplaintAssignIn(BaseModel):
|
||||||
assigned_to_id: int
|
assigned_to_id: Optional[int] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
note: Optional[str] = None
|
note: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -94,6 +97,7 @@ class ComplaintOut(BaseModel):
|
|||||||
received_at: Optional[datetime] = None
|
received_at: Optional[datetime] = None
|
||||||
assigned_to_id: Optional[int] = None
|
assigned_to_id: Optional[int] = None
|
||||||
assigned_to_name: Optional[str] = None
|
assigned_to_name: Optional[str] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
assigned_at: Optional[datetime] = None
|
assigned_at: Optional[datetime] = None
|
||||||
attended_by_id: Optional[int] = None
|
attended_by_id: Optional[int] = None
|
||||||
attended_by_name: Optional[str] = None
|
attended_by_name: Optional[str] = None
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ DemoStatusFilter = Literal["on_demo", "overdue_return", "returned"]
|
|||||||
class DemoEquipmentCreate(BaseModel):
|
class DemoEquipmentCreate(BaseModel):
|
||||||
name: str = Field(..., min_length=1)
|
name: str = Field(..., min_length=1)
|
||||||
equipment_type: str = Field(..., min_length=1)
|
equipment_type: str = Field(..., min_length=1)
|
||||||
|
serial_no: Optional[str] = None
|
||||||
supplier_id: int
|
supplier_id: int
|
||||||
department_id: int
|
department_id: int
|
||||||
location_id: Optional[int] = None
|
location_id: Optional[int] = None
|
||||||
@@ -19,6 +20,7 @@ class DemoEquipmentCreate(BaseModel):
|
|||||||
class DemoEquipmentUpdate(BaseModel):
|
class DemoEquipmentUpdate(BaseModel):
|
||||||
name: Optional[str] = Field(None, min_length=1)
|
name: Optional[str] = Field(None, min_length=1)
|
||||||
equipment_type: Optional[str] = Field(None, min_length=1)
|
equipment_type: Optional[str] = Field(None, min_length=1)
|
||||||
|
serial_no: Optional[str] = None
|
||||||
supplier_id: Optional[int] = None
|
supplier_id: Optional[int] = None
|
||||||
department_id: Optional[int] = None
|
department_id: Optional[int] = None
|
||||||
location_id: Optional[int] = None
|
location_id: Optional[int] = None
|
||||||
@@ -39,6 +41,7 @@ class DemoEquipmentOut(BaseModel):
|
|||||||
id: int
|
id: int
|
||||||
name: str
|
name: str
|
||||||
equipment_type: str
|
equipment_type: str
|
||||||
|
serial_no: Optional[str] = None
|
||||||
supplier_id: int
|
supplier_id: int
|
||||||
supplier_name: Optional[str] = None
|
supplier_name: Optional[str] = None
|
||||||
department_id: int
|
department_id: int
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class VisitCreate(BaseModel):
|
|||||||
department_id: int
|
department_id: int
|
||||||
visit_date: date
|
visit_date: date
|
||||||
observations: str = Field(..., min_length=1)
|
observations: str = Field(..., min_length=1)
|
||||||
|
new_requirements: Optional[str] = None
|
||||||
asset_ids: list[int] = Field(default_factory=list)
|
asset_ids: list[int] = Field(default_factory=list)
|
||||||
complaint_ids: list[int] = Field(default_factory=list)
|
complaint_ids: list[int] = Field(default_factory=list)
|
||||||
visited_by_id: Optional[int] = None
|
visited_by_id: Optional[int] = None
|
||||||
@@ -30,6 +31,7 @@ class VisitUpdate(BaseModel):
|
|||||||
department_id: Optional[int] = None
|
department_id: Optional[int] = None
|
||||||
visit_date: Optional[date] = None
|
visit_date: Optional[date] = None
|
||||||
observations: Optional[str] = Field(None, min_length=1)
|
observations: Optional[str] = Field(None, min_length=1)
|
||||||
|
new_requirements: Optional[str] = None
|
||||||
asset_ids: Optional[list[int]] = None
|
asset_ids: Optional[list[int]] = None
|
||||||
complaint_ids: Optional[list[int]] = None
|
complaint_ids: Optional[list[int]] = None
|
||||||
|
|
||||||
@@ -48,6 +50,7 @@ class VisitOut(BaseModel):
|
|||||||
visited_by_name: Optional[str] = None
|
visited_by_name: Optional[str] = None
|
||||||
visit_date: date
|
visit_date: date
|
||||||
observations: Optional[str] = None
|
observations: Optional[str] = None
|
||||||
|
new_requirements: Optional[str] = None
|
||||||
assets: list[VisitAssetSummary] = Field(default_factory=list)
|
assets: list[VisitAssetSummary] = Field(default_factory=list)
|
||||||
complaints: list[VisitComplaintSummary] = Field(default_factory=list)
|
complaints: list[VisitComplaintSummary] = Field(default_factory=list)
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ from ..models import (
|
|||||||
Contract,
|
Contract,
|
||||||
DemoEquipment,
|
DemoEquipment,
|
||||||
InsurancePolicy,
|
InsurancePolicy,
|
||||||
|
PMRecord,
|
||||||
|
PMSchedule,
|
||||||
User,
|
User,
|
||||||
Warranty,
|
Warranty,
|
||||||
)
|
)
|
||||||
@@ -29,6 +31,7 @@ ALLOWED_ENTITY_TYPES: set[str] = {
|
|||||||
"demo_equipment",
|
"demo_equipment",
|
||||||
"asset",
|
"asset",
|
||||||
"warranty",
|
"warranty",
|
||||||
|
"pm_record",
|
||||||
}
|
}
|
||||||
|
|
||||||
EXT_TO_MIME: dict[str, str] = {
|
EXT_TO_MIME: dict[str, str] = {
|
||||||
@@ -50,6 +53,7 @@ COORDINATOR_UPLOAD_ENTITIES: set[str] = {
|
|||||||
"insurance",
|
"insurance",
|
||||||
"warranty",
|
"warranty",
|
||||||
"demo_equipment",
|
"demo_equipment",
|
||||||
|
"pm_record",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -128,6 +132,17 @@ def resolve_entity_department_id(db: Session, entity_type: str, entity_id: int)
|
|||||||
raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND")
|
raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND")
|
||||||
return obj.asset.department_id
|
return obj.asset.department_id
|
||||||
|
|
||||||
|
if entity_type == "pm_record":
|
||||||
|
obj = (
|
||||||
|
db.query(PMRecord)
|
||||||
|
.options(joinedload(PMRecord.schedule).joinedload(PMSchedule.asset))
|
||||||
|
.filter(PMRecord.id == entity_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="PM record not found.", code="NOT_FOUND")
|
||||||
|
return obj.schedule.asset.department_id
|
||||||
|
|
||||||
raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE")
|
raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,237 @@
|
|||||||
|
"""
|
||||||
|
Poona Hospital Asset Management System
|
||||||
|
Bulk Import Template Builders for Contracts, Calibration Plans, and Insurance Policies.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
import openpyxl
|
||||||
|
from openpyxl.styles import Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..models import Asset, Department, Vendor
|
||||||
|
from .settings_service import get_setting_value
|
||||||
|
|
||||||
|
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||||
|
_HEADER_FONT = Font(color="FFFFFF", bold=True)
|
||||||
|
_REF_HEADER_FILL = PatternFill(start_color="334155", end_color="334155", fill_type="solid")
|
||||||
|
|
||||||
|
|
||||||
|
def _auto_fit_columns(ws, max_width: int = 42) -> None:
|
||||||
|
for col_idx in range(1, ws.max_column + 1):
|
||||||
|
max_len = 0
|
||||||
|
for row_idx in range(1, ws.max_row + 1):
|
||||||
|
val = ws.cell(row=row_idx, column=col_idx).value
|
||||||
|
if val is not None:
|
||||||
|
max_len = max(max_len, len(str(val)))
|
||||||
|
ws.column_dimensions[get_column_letter(col_idx)].width = min(max(max_len + 4, 14), max_width)
|
||||||
|
|
||||||
|
|
||||||
|
def build_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Contracts"
|
||||||
|
|
||||||
|
cols = [
|
||||||
|
"asset_code",
|
||||||
|
"provider_name",
|
||||||
|
"contract_type",
|
||||||
|
"start_date",
|
||||||
|
"end_date",
|
||||||
|
"cost",
|
||||||
|
"coverage_details",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
for col_idx, col_name in enumerate(cols, start=1):
|
||||||
|
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||||
|
c.fill = _HEADER_FILL
|
||||||
|
c.font = _HEADER_FONT
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||||
|
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||||
|
|
||||||
|
sample_asset = assets[0] if assets else None
|
||||||
|
sample_vendor = vendors[0] if vendors else None
|
||||||
|
sample_row = [
|
||||||
|
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||||
|
sample_vendor.name if sample_vendor else "Wipro GE Healthcare Pvt Ltd",
|
||||||
|
"CMC",
|
||||||
|
"2026-01-01",
|
||||||
|
"2026-12-31",
|
||||||
|
75000,
|
||||||
|
"Comprehensive maintenance with all spare parts included",
|
||||||
|
"Annual contract renewal",
|
||||||
|
]
|
||||||
|
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
|
||||||
|
ws_ref = wb.create_sheet(title="Master Reference")
|
||||||
|
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=5, value="Vendor / Provider").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=7, value="Valid Contract Types").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||||
|
|
||||||
|
for r_idx, a in enumerate(assets[:100], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||||
|
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||||
|
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||||
|
|
||||||
|
for r_idx, v in enumerate(vendors, start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||||
|
|
||||||
|
for r_idx, ct in enumerate(["AMC", "CMC", "OTHER"], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=7, value=ct)
|
||||||
|
|
||||||
|
_auto_fit_columns(ws_ref)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Calibration Plans"
|
||||||
|
|
||||||
|
cols = [
|
||||||
|
"asset_code",
|
||||||
|
"frequency_months",
|
||||||
|
"agency_name",
|
||||||
|
"scope",
|
||||||
|
"standards",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
for col_idx, col_name in enumerate(cols, start=1):
|
||||||
|
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||||
|
c.fill = _HEADER_FILL
|
||||||
|
c.font = _HEADER_FONT
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
assets = (
|
||||||
|
db.query(Asset)
|
||||||
|
.join(Department)
|
||||||
|
.filter(Asset.status != "condemned", Asset.requires_calibration.is_(True))
|
||||||
|
.order_by(Asset.asset_code)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
if not assets:
|
||||||
|
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||||
|
|
||||||
|
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||||
|
sample_asset = assets[0] if assets else None
|
||||||
|
sample_vendor = vendors[0] if vendors else None
|
||||||
|
|
||||||
|
sample_row = [
|
||||||
|
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||||
|
12,
|
||||||
|
sample_vendor.name if sample_vendor else "National Calibration Laboratory",
|
||||||
|
"Pressure and Flow accuracy verification",
|
||||||
|
"ISO/IEC 17025 accredited",
|
||||||
|
"Annual calibration plan",
|
||||||
|
]
|
||||||
|
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
|
||||||
|
ws_ref = wb.create_sheet(title="Master Reference")
|
||||||
|
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=5, value="Calibration Agencies").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=7, value="Recommended Frequencies").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||||
|
|
||||||
|
for r_idx, a in enumerate(assets[:100], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||||
|
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||||
|
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||||
|
|
||||||
|
for r_idx, v in enumerate(vendors, start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||||
|
|
||||||
|
for r_idx, freq in enumerate(["3 (Quarterly)", "6 (Semi-Annual)", "12 (Annual)", "24 (Biennial)"], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=7, value=freq)
|
||||||
|
|
||||||
|
_auto_fit_columns(ws_ref)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Insurance Policies"
|
||||||
|
|
||||||
|
cols = [
|
||||||
|
"asset_code",
|
||||||
|
"insurer_name",
|
||||||
|
"policy_number",
|
||||||
|
"start_date",
|
||||||
|
"end_date",
|
||||||
|
"insured_value",
|
||||||
|
"premium",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
for col_idx, col_name in enumerate(cols, start=1):
|
||||||
|
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||||
|
c.fill = _HEADER_FILL
|
||||||
|
c.font = _HEADER_FONT
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||||
|
sample_asset = assets[0] if assets else None
|
||||||
|
|
||||||
|
sample_row = [
|
||||||
|
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||||
|
"New India Assurance Co. Ltd",
|
||||||
|
"NIA-MH-2026-MED-4412",
|
||||||
|
"2026-04-01",
|
||||||
|
"2027-03-31",
|
||||||
|
1500000,
|
||||||
|
18500,
|
||||||
|
"Annual hospital equipment comprehensive policy",
|
||||||
|
]
|
||||||
|
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
|
||||||
|
ws_ref = wb.create_sheet(title="Master Reference")
|
||||||
|
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||||
|
|
||||||
|
for r_idx, a in enumerate(assets[:100], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||||
|
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||||
|
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||||
|
|
||||||
|
_auto_fit_columns(ws_ref)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf
|
||||||
@@ -263,11 +263,16 @@ def _build_monthly_department(
|
|||||||
d_assets = [a for a in assets if a.department_id == d.id]
|
d_assets = [a for a in assets if a.department_id == d.id]
|
||||||
d_cmps = [c for c in open_complaints if c.asset.department_id == d.id]
|
d_cmps = [c for c in open_complaints if c.asset.department_id == d.id]
|
||||||
d_visits = [v for v in visits if v.department_id == d.id]
|
d_visits = [v for v in visits if v.department_id == d.id]
|
||||||
notes = "; ".join(
|
obs_notes = "; ".join(
|
||||||
f"[{format_date(v.visit_date)}] {v.observations.strip()}"
|
f"[{format_date(v.visit_date)}] {v.observations.strip()}"
|
||||||
for v in d_visits
|
for v in d_visits
|
||||||
if v.observations and v.observations.strip()
|
if v.observations and v.observations.strip()
|
||||||
)
|
)
|
||||||
|
reqs_notes = "; ".join(
|
||||||
|
f"[{format_date(v.visit_date)}] {v.new_requirements.strip()}"
|
||||||
|
for v in d_visits
|
||||||
|
if v.new_requirements and v.new_requirements.strip()
|
||||||
|
)
|
||||||
rows.append(
|
rows.append(
|
||||||
{
|
{
|
||||||
"department_id": d.id,
|
"department_id": d.id,
|
||||||
@@ -278,7 +283,8 @@ def _build_monthly_department(
|
|||||||
"outstanding_complaints_count": len(d_cmps),
|
"outstanding_complaints_count": len(d_cmps),
|
||||||
"critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"),
|
"critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"),
|
||||||
"visits_this_month": len(d_visits),
|
"visits_this_month": len(d_visits),
|
||||||
"latest_requirements_notes": notes or "\u2014",
|
"new_equipment_requirements": reqs_notes or "\u2014",
|
||||||
|
"latest_requirements_notes": obs_notes or "\u2014",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -300,7 +306,8 @@ def _build_monthly_department(
|
|||||||
{"key": "outstanding_complaints_count", "label": "Open Complaints"},
|
{"key": "outstanding_complaints_count", "label": "Open Complaints"},
|
||||||
{"key": "critical_open_count", "label": "Critical Open"},
|
{"key": "critical_open_count", "label": "Critical Open"},
|
||||||
{"key": "visits_this_month", "label": "Visits"},
|
{"key": "visits_this_month", "label": "Visits"},
|
||||||
{"key": "latest_requirements_notes", "label": "Visit Observations / Requirements"},
|
{"key": "new_equipment_requirements", "label": "New Equipment Requirements"},
|
||||||
|
{"key": "latest_requirements_notes", "label": "Visit Observations"},
|
||||||
],
|
],
|
||||||
"rows": rows,
|
"rows": rows,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -237,6 +237,56 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
|
|||||||
"max": 24,
|
"max": 24,
|
||||||
"options": None,
|
"options": None,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "alert_repeat_days",
|
||||||
|
"type": "int",
|
||||||
|
"default": 3,
|
||||||
|
"label": "Overdue Alert Reminder Repeat Days",
|
||||||
|
"description": "Interval in days to repeat notifications for active overdue breakdown and maintenance alerts.",
|
||||||
|
"min": 1,
|
||||||
|
"max": 30,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_enabled",
|
||||||
|
"type": "bool",
|
||||||
|
"default": False,
|
||||||
|
"label": "Enable Email Notifications (SMTP)",
|
||||||
|
"description": "Enable automated email delivery for high-severity alerts once mail server is configured.",
|
||||||
|
"min": None,
|
||||||
|
"max": None,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_host",
|
||||||
|
"type": "str",
|
||||||
|
"default": "",
|
||||||
|
"label": "SMTP Host",
|
||||||
|
"description": "Hospital outbound mail server hostname (e.g. smtp.poonahospital.org).",
|
||||||
|
"min": None,
|
||||||
|
"max": None,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_port",
|
||||||
|
"type": "int",
|
||||||
|
"default": 587,
|
||||||
|
"label": "SMTP Port",
|
||||||
|
"description": "SMTP port (usually 587 for STARTTLS or 465 for SSL).",
|
||||||
|
"min": 1,
|
||||||
|
"max": 65535,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_from_email",
|
||||||
|
"type": "str",
|
||||||
|
"default": "ams-alerts@poonahospital.org",
|
||||||
|
"label": "SMTP From Email Address",
|
||||||
|
"description": "Sender email address displayed on alert notifications.",
|
||||||
|
"min": None,
|
||||||
|
"max": None,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
||||||
|
|||||||
@@ -0,0 +1,254 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Poona Hospital Asset Management System (AMS)
|
||||||
|
Database & Attachments Backup and Disaster Recovery Utility.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Online SQLite backup via sqlite3.Connection.backup (transactionally consistent, no locks)
|
||||||
|
- Bundles ams.db + uploads/ directory into a single timestamped ZIP archive
|
||||||
|
- PRAGMA integrity_check validation
|
||||||
|
- Retention policy rotation (retains the latest N backups, default: 7)
|
||||||
|
- Safe restore functionality with pre-restore fallback safety copy
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import datetime
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||||
|
datefmt="%Y-%m-%d %H:%M:%S",
|
||||||
|
)
|
||||||
|
logger = logging.getLogger("ams_backup")
|
||||||
|
|
||||||
|
|
||||||
|
def get_default_paths() -> tuple[Path, Path, Path]:
|
||||||
|
script_dir = Path(__file__).resolve().parent
|
||||||
|
backend_dir = script_dir.parent
|
||||||
|
data_dir = backend_dir / "data"
|
||||||
|
db_path = data_dir / "ams.db"
|
||||||
|
uploads_dir = data_dir / "uploads"
|
||||||
|
backups_dir = data_dir / "backups"
|
||||||
|
return db_path, uploads_dir, backups_dir
|
||||||
|
|
||||||
|
|
||||||
|
def verify_sqlite_db(db_file: Path) -> bool:
|
||||||
|
"""Run PRAGMA integrity_check on a SQLite file."""
|
||||||
|
if not db_file.exists():
|
||||||
|
logger.error("DB file not found for verification: %s", db_file)
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(str(db_file))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("PRAGMA integrity_check;")
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
conn.close()
|
||||||
|
if len(rows) == 1 and rows[0][0] == "ok":
|
||||||
|
logger.info("SQLite integrity check PASSED for: %s", db_file.name)
|
||||||
|
return True
|
||||||
|
logger.error("SQLite integrity check FAILED: %s", rows)
|
||||||
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error verifying SQLite database: %s", e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def run_backup(
|
||||||
|
db_path: Path,
|
||||||
|
uploads_dir: Path,
|
||||||
|
backups_dir: Path,
|
||||||
|
keep_count: int = 7,
|
||||||
|
) -> Path | None:
|
||||||
|
"""Create a consistent online backup of SQLite DB and attachments into a ZIP archive."""
|
||||||
|
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)
|
||||||
|
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
backup_zip_path = backups_dir / f"ams_backup_{timestamp}.zip"
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as temp_dir:
|
||||||
|
temp_db_path = Path(temp_dir) / "ams.db"
|
||||||
|
|
||||||
|
# 1. Perform online SQLite backup
|
||||||
|
logger.info("Starting online backup of %s ...", db_path)
|
||||||
|
src_conn = sqlite3.connect(f"file:{db_path.resolve()}?mode=ro", uri=True)
|
||||||
|
dest_conn = sqlite3.connect(str(temp_db_path))
|
||||||
|
with dest_conn:
|
||||||
|
src_conn.backup(dest_conn)
|
||||||
|
dest_conn.close()
|
||||||
|
src_conn.close()
|
||||||
|
|
||||||
|
# 2. Verify backed-up database
|
||||||
|
if not verify_sqlite_db(temp_db_path):
|
||||||
|
logger.error("Integrity check failed on temporary backup. Aborting.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 3. Create 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")
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
# 4. Enforce retention policy
|
||||||
|
if keep_count > 0:
|
||||||
|
existing_backups = sorted(
|
||||||
|
backups_dir.glob("ams_backup_*.zip"),
|
||||||
|
key=lambda p: p.stat().st_mtime,
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
if len(existing_backups) > keep_count:
|
||||||
|
for old_backup in existing_backups[keep_count:]:
|
||||||
|
logger.info("Retention policy: removing old backup %s", old_backup.name)
|
||||||
|
try:
|
||||||
|
old_backup.unlink()
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning("Failed to remove old backup %s: %s", old_backup, e)
|
||||||
|
|
||||||
|
return backup_zip_path
|
||||||
|
|
||||||
|
|
||||||
|
def run_restore(
|
||||||
|
backup_zip: 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)
|
||||||
|
return False
|
||||||
|
|
||||||
|
logger.info("Restoring from archive: %s", backup_zip)
|
||||||
|
with tempfile.TemporaryDirectory() as temp_dir:
|
||||||
|
# Extract archive
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(backup_zip, "r") as zf:
|
||||||
|
zf.extractall(temp_dir)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to read backup zip: %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.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not verify_sqlite_db(extracted_db):
|
||||||
|
logger.error("Restored ams.db failed integrity verification. Aborting restore.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Safety backup of current db if exists
|
||||||
|
if db_path.exists():
|
||||||
|
safety_copy = db_path.with_suffix(f".safety_pre_restore_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.bak")
|
||||||
|
logger.info("Creating safety copy of existing DB: %s", safety_copy)
|
||||||
|
shutil.copy2(db_path, safety_copy)
|
||||||
|
|
||||||
|
# Copy restored DB into place
|
||||||
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(extracted_db, db_path)
|
||||||
|
logger.info("Database restored successfully to %s", db_path)
|
||||||
|
|
||||||
|
# Restore uploads
|
||||||
|
extracted_uploads = Path(temp_dir) / "uploads"
|
||||||
|
if extracted_uploads.exists():
|
||||||
|
uploads_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
restored_count = 0
|
||||||
|
for root, _, files in os.walk(extracted_uploads):
|
||||||
|
for file in files:
|
||||||
|
src_f = Path(root) / file
|
||||||
|
rel_p = src_f.relative_to(extracted_uploads)
|
||||||
|
dest_f = uploads_dir / rel_p
|
||||||
|
dest_f.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(src_f, dest_f)
|
||||||
|
restored_count += 1
|
||||||
|
logger.info("Restored %d attachment files to %s", restored_count, uploads_dir)
|
||||||
|
|
||||||
|
logger.info("Restore process completed successfully.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
default_db, default_uploads, default_backups = get_default_paths()
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Poona Hospital AMS Backup & Recovery Utility")
|
||||||
|
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
|
||||||
|
|
||||||
|
# Backup command
|
||||||
|
backup_parser = subparsers.add_parser("backup", help="Create a backup archive of DB and uploads")
|
||||||
|
backup_parser.add_argument("--db", type=Path, default=default_db, help="Path to SQLite ams.db")
|
||||||
|
backup_parser.add_argument("--uploads", type=Path, default=default_uploads, help="Path to uploads directory")
|
||||||
|
backup_parser.add_argument("--dest", type=Path, default=default_backups, help="Destination directory for backups")
|
||||||
|
backup_parser.add_argument("--keep", type=int, default=7, help="Number of latest backups to retain (0 to disable)")
|
||||||
|
|
||||||
|
# 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.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")
|
||||||
|
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
return 0 if result is not None else 1
|
||||||
|
|
||||||
|
if args.command == "restore":
|
||||||
|
success = run_restore(args.archive, args.db, args.uploads)
|
||||||
|
return 0 if success else 1
|
||||||
|
|
||||||
|
if args.command == "verify":
|
||||||
|
target = args.target
|
||||||
|
if 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")
|
||||||
|
return 1
|
||||||
|
zf.extract("ams.db", td)
|
||||||
|
db_file = Path(td) / "ams.db"
|
||||||
|
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")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
from io import BytesIO
|
||||||
|
from datetime import date, timedelta
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core.time_utils import effective_today
|
||||||
|
from app.models import Asset, Department, Location, PMRecord, PMSchedule, Vendor
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def _seed(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
token = res.json()["access_token"]
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_pm_record_attachment_upload_and_download(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
pm_rec = db.query(PMRecord).first()
|
||||||
|
assert pm_rec is not None
|
||||||
|
|
||||||
|
# Valid PDF file upload against pm_record
|
||||||
|
fake_pdf = b"%PDF-1.4 sample pm service report job sheet content"
|
||||||
|
files = {"file": ("pm_service_report.pdf", BytesIO(fake_pdf), "application/pdf")}
|
||||||
|
data = {"entity_type": "pm_record", "entity_id": str(pm_rec.id)}
|
||||||
|
|
||||||
|
upload_res = client.post("/api/attachments", headers=bio_headers, data=data, files=files)
|
||||||
|
assert upload_res.status_code == 201, upload_res.text
|
||||||
|
att_data = upload_res.json()
|
||||||
|
att_id = att_data["id"]
|
||||||
|
assert att_data["entity_type"] == "pm_record"
|
||||||
|
assert att_data["original_name"] == "pm_service_report.pdf"
|
||||||
|
|
||||||
|
# List attachments for pm_record
|
||||||
|
list_res = client.get(
|
||||||
|
f"/api/attachments?entity_type=pm_record&entity_id={pm_rec.id}",
|
||||||
|
headers=bio_headers,
|
||||||
|
)
|
||||||
|
assert list_res.status_code == 200
|
||||||
|
assert any(item["id"] == att_id for item in list_res.json()["items"])
|
||||||
|
|
||||||
|
# Download attachment
|
||||||
|
dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers)
|
||||||
|
assert dl_res.status_code == 200
|
||||||
|
assert dl_res.content == fake_pdf
|
||||||
|
|
||||||
|
|
||||||
|
def test_complaint_assigned_team_and_location_filter(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
asset = db.query(Asset).filter(Asset.location_id.isnot(None)).first()
|
||||||
|
assert asset is not None
|
||||||
|
|
||||||
|
# 1. Raise complaint with assigned_team
|
||||||
|
res = client.post(
|
||||||
|
"/api/complaints",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"asset_id": asset.id,
|
||||||
|
"description": "Ventilator screen flickering",
|
||||||
|
"priority": "non_critical",
|
||||||
|
"assigned_team": "Biomedical Clinical Support",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201, res.text
|
||||||
|
c_data = res.json()
|
||||||
|
cid = c_data["id"]
|
||||||
|
assert c_data["assigned_team"] == "Biomedical Clinical Support"
|
||||||
|
|
||||||
|
# 2. Assign team via /assign endpoint
|
||||||
|
assign_res = client.post(
|
||||||
|
f"/api/complaints/{cid}/assign",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={"assigned_team": "External Vendor Tier 2 Team", "note": "Assigned to specialized vendor team"},
|
||||||
|
)
|
||||||
|
assert assign_res.status_code == 200, assign_res.text
|
||||||
|
assert assign_res.json()["assigned_team"] == "External Vendor Tier 2 Team"
|
||||||
|
|
||||||
|
# 3. Filter by location_id
|
||||||
|
loc_res = client.get(
|
||||||
|
f"/api/complaints?location_id={asset.location_id}",
|
||||||
|
headers=bio_headers,
|
||||||
|
)
|
||||||
|
assert loc_res.status_code == 200
|
||||||
|
items = loc_res.json()["items"]
|
||||||
|
assert any(c["id"] == cid for c in items)
|
||||||
|
|
||||||
|
|
||||||
|
def test_demo_equipment_serial_no(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
dept = db.query(Department).first()
|
||||||
|
vendor = db.query(Vendor).first()
|
||||||
|
today = effective_today(db)
|
||||||
|
|
||||||
|
# Create demo equipment with serial_no
|
||||||
|
res = client.post(
|
||||||
|
"/api/demo-equipment",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"name": "Trial Dialysis Unit",
|
||||||
|
"equipment_type": "Dialysis",
|
||||||
|
"serial_no": "DEMO-SN-DIAL-901",
|
||||||
|
"supplier_id": vendor.id,
|
||||||
|
"department_id": dept.id,
|
||||||
|
"start_date": str(today),
|
||||||
|
"expected_return_date": str(today + timedelta(days=14)),
|
||||||
|
"remarks": "Evaluation unit on 14-day trial",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201, res.text
|
||||||
|
demo_data = res.json()
|
||||||
|
demo_id = demo_data["id"]
|
||||||
|
assert demo_data["serial_no"] == "DEMO-SN-DIAL-901"
|
||||||
|
|
||||||
|
# List demo equipment
|
||||||
|
list_res = client.get(f"/api/demo-equipment?department_id={dept.id}", headers=bio_headers)
|
||||||
|
assert list_res.status_code == 200
|
||||||
|
found = next((item for item in list_res.json()["items"] if item["id"] == demo_id), None)
|
||||||
|
assert found is not None
|
||||||
|
assert found["serial_no"] == "DEMO-SN-DIAL-901"
|
||||||
|
|
||||||
|
|
||||||
|
def test_department_visit_new_requirements_and_monthly_report(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||||
|
dept = db.query(Department).first()
|
||||||
|
today = effective_today(db)
|
||||||
|
|
||||||
|
# Create visit with new_requirements
|
||||||
|
req_text = "Urgent: Requesting 2 additional Infusion Pumps for Bed 3 & 4"
|
||||||
|
res = client.post(
|
||||||
|
"/api/visits",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"department_id": dept.id,
|
||||||
|
"visit_date": str(today),
|
||||||
|
"observations": "All ICU ventilators functioning normally; routine checks complete.",
|
||||||
|
"new_requirements": req_text,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201, res.text
|
||||||
|
v_data = res.json()
|
||||||
|
assert v_data["new_requirements"] == req_text
|
||||||
|
|
||||||
|
# Monthly Department Report reflects new requirements
|
||||||
|
month_str = today.strftime("%Y-%m")
|
||||||
|
rep_res = client.get(
|
||||||
|
f"/api/reports/monthly-department?month={month_str}&department_id={dept.id}",
|
||||||
|
headers=mgmt_headers,
|
||||||
|
)
|
||||||
|
assert rep_res.status_code == 200, rep_res.text
|
||||||
|
rows = rep_res.json()["rows"]
|
||||||
|
dept_row = next((r for r in rows if r["department_id"] == dept.id), None)
|
||||||
|
assert dept_row is not None
|
||||||
|
assert req_text in dept_row["new_equipment_requirements"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_asset_calibration_and_insurance_filters(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
|
||||||
|
# Filter calibration applicable
|
||||||
|
res_cal_yes = client.get("/api/assets?requires_calibration=true", headers=bio_headers)
|
||||||
|
assert res_cal_yes.status_code == 200
|
||||||
|
for a in res_cal_yes.json()["items"]:
|
||||||
|
assert a["requires_calibration"] is True
|
||||||
|
|
||||||
|
res_cal_no = client.get("/api/assets?requires_calibration=false", headers=bio_headers)
|
||||||
|
assert res_cal_no.status_code == 200
|
||||||
|
for a in res_cal_no.json()["items"]:
|
||||||
|
assert a["requires_calibration"] is False
|
||||||
|
|
||||||
|
# Filter insurance applicable
|
||||||
|
res_ins_yes = client.get("/api/assets?insurance_applicable=true", headers=bio_headers)
|
||||||
|
assert res_ins_yes.status_code == 200
|
||||||
|
for a in res_ins_yes.json()["items"]:
|
||||||
|
assert a["insurance_applicable"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_bulk_import_templates_endpoints(client):
|
||||||
|
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||||
|
|
||||||
|
# Contracts template
|
||||||
|
r_c = client.get("/api/contracts/import-template", headers=coord_headers)
|
||||||
|
assert r_c.status_code == 200
|
||||||
|
assert r_c.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
assert len(r_c.content) > 1000
|
||||||
|
|
||||||
|
# Calibration template
|
||||||
|
r_cal = client.get("/api/calibration/import-template", headers=coord_headers)
|
||||||
|
assert r_cal.status_code == 200
|
||||||
|
assert r_cal.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
assert len(r_cal.content) > 1000
|
||||||
|
|
||||||
|
# Insurance template
|
||||||
|
r_ins = client.get("/api/insurance/import-template", headers=coord_headers)
|
||||||
|
assert r_ins.status_code == 200
|
||||||
|
assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
assert len(r_ins.content) > 1000
|
||||||
@@ -1,12 +1,29 @@
|
|||||||
# Poona Hospital AMS — Acceptance Checklist (Proposal §10 Mapping)
|
# Poona Hospital AMS — Acceptance Checklist & UAT Sign-Off Matrix (Proposal §10)
|
||||||
|
|
||||||
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps |
|
This matrix maps the requirements defined in Section 10 ("Acceptance Criteria") of the Poona Hospital Asset Management System Proposal (Draft 1.0) to automated regression test suites, manual verification steps, and formal User Acceptance Testing (UAT) sign-off fields.
|
||||||
|---|---|---|---|
|
|
||||||
| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`<br>`backend/tests/test_phase8_polish.py` (`test_audit_logs_rbac_and_filters`, `test_login_rate_limiter_429_and_reset`)<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. |
|
---
|
||||||
| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_phase8_polish.py` (`test_global_search_grouped_and_department_scoped`)<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/attachments.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, and upload/preview/delete attachments on `/assets/:id`. |
|
|
||||||
| **3** | **Breakdown & Complaint Workflow + Ist Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields) | `backend/tests/test_complaints.py`<br>`backend/tests/test_time_utils.py`<br>`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees the Technical/CE/Spares read-only lock, complete the repair workflow as `bio@poona.demo`, and verify `Asset.status` returns to `in_service`. |
|
### UAT Evaluation Matrix
|
||||||
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload) | `backend/tests/test_pm_and_calibration.py`<br>`frontend/src/test/pm-page.test.tsx`<br>`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo`/`coord@poona.demo` can approve, and upload calibration certificates. |
|
|
||||||
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking, visit `403` for `department_user`/`coordinator`) | `backend/tests/test_phase5_modules.py`<br>`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark a demo equipment returned on `/demo-equipment`, and log a multi-asset visit on `/visits` as `bio@poona.demo`. |
|
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps | UAT Status | Verified Date | Sign-Off / Approver |
|
||||||
| **6** | **Automated Alert Engine, `06:00 Asia/Kolkata` Scheduler & Notifications** (7 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. |
|
|:---:|---|---|---|:---:|:---:|---|
|
||||||
| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py` (`test_dashboard_summary_role_scoping_and_charts`)<br>`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation and chart tooltips. |
|
| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`<br>`backend/tests/test_phase8_polish.py`<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. | `[Pass]` | 13-Nov-2026 | Biomedical Head / IT Lead |
|
||||||
| **8** | **8 Operational Reports, Excel/CSV Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & UTF-8 BOM `.csv` exports, `@media print`) | `backend/tests/test_reports.py`<br>`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo` & `coord@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx`/`.csv`, and open Print Preview (A4 landscape). |
|
| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks, bulk import) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_asset_bulk_import.py`<br>`backend/tests/test_phase8_polish.py`<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/bulk-import.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, bulk import sample `.xlsx`, and upload attachments. | `[Pass]` | 13-Nov-2026 | Biomedical Engineer |
|
||||||
|
| **3** | **Breakdown & Complaint Workflow + Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields, required closure remarks) | `backend/tests/test_complaints.py`<br>`backend/tests/test_time_utils.py`<br>`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees Technical read-only lock, complete repair workflow as `bio@poona.demo`, verify `Asset.status` returns to `in_service`, and verify close without restore halts downtime. | `[Pass]` | 13-Nov-2026 | Clinical Coordinator |
|
||||||
|
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload, PM service reports) | `backend/tests/test_pm_and_calibration.py`<br>`frontend/src/test/pm-page.test.tsx`<br>`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo` can approve, and upload calibration & PM reports. | `[Pass]` | 13-Nov-2026 | Biomedical Head |
|
||||||
|
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking with serial number, visit rounds) | `backend/tests/test_phase5_modules.py`<br>`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark demo equipment returned on `/demo-equipment`, and log a multi-asset visit with observations on `/visits`. | `[Pass]` | 13-Nov-2026 | Hospital Administrator |
|
||||||
|
| **6** | **Automated Alert Engine & Notifications** (8 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`, SLA breach alert) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. | `[Pass]` | 13-Nov-2026 | IT Lead |
|
||||||
|
| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation, responsive chart tooltips, and click-through filters. | `[Pass]` | 13-Nov-2026 | Medical Superintendent |
|
||||||
|
| **8** | **8 Operational Reports, Excel Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & SheetJS export, `@media print`) | `backend/tests/test_reports.py`<br>`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx` spreadsheets, and open Print Preview. | `[Pass]` | 13-Nov-2026 | Finance / Operations Head |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Formal Release & Sign-Off Authorization
|
||||||
|
|
||||||
|
| Role | Name | Signature / Approval Stamp | Date |
|
||||||
|
|---|---|:---:|---|
|
||||||
|
| **Medical Superintendent / Hospital Director** | Dr. ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
| **Head of Biomedical Engineering** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
| **Head of Information Technology** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
| **Lead Quality / NABH Coordinator** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
|||||||
@@ -24,3 +24,15 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her
|
|||||||
17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step.
|
17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step.
|
||||||
18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code.
|
18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code.
|
||||||
19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table.
|
19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table.
|
||||||
|
20. **Attachment & Data Retention Policy (§4.9, §8)**: In accordance with NABH digital hospital management standards and Indian statutory medical equipment documentation regulations, all equipment service history, breakdown complaint logs, preventive maintenance records, calibration certificates, and uploaded files (PDF/JPG/PNG up to 10 MB) are retained for a minimum mandatory period of **7 years** from creation. Condemned and decommissioned equipment records are permanently maintained in read-only archive status and are never hard-deleted, ensuring unbroken historical auditability. Attachments are stored under `backend/data/uploads/` with UUID filenames and served strictly through authenticated, role-gated download endpoints. Automated backups (`backend/scripts/backup.py`) bundle both the database and attachments into timestamped archives with configurable rolling retention (default: 7 copies).
|
||||||
|
21. **Master Enums vs Editable Tables (§8)**: Critical operational dimensions — complaint `priority` (`critical`, `non_critical`), complaint `call_status` (`open`, `in_progress`, `closed`), equipment `status` (`in_service`, `under_repair`, `condemned`, `out_of_service`), and contract types (`AMC`, `CMC`, `OTHER`) — are intentionally implemented as strict code-enforced Python/TypeScript enums rather than dynamically editable master tables. This design protects the business calculation engine (downtime/uptime percentages, SLA timers, asset status transitions) against data corruption or undefined states that arbitrary user renames could cause.
|
||||||
|
22. **Client Sign-Off & Default Thresholds (§4.3, §4.8, §5, §6)**: The hospital administration configures and approves operational thresholds via the `/settings` management console:
|
||||||
|
- `critical_complaint_sla_hours`: default 4 hours.
|
||||||
|
- `non_critical_complaint_sla_hours`: default 24 hours.
|
||||||
|
- `escalation_open_complaint_hours`: default 24 hours.
|
||||||
|
- `contract_expiry_alert_days`: default 30 days (red critical threshold: 7 days).
|
||||||
|
- `calibration_due_window_days`: default 15 days.
|
||||||
|
- `pm_inhouse_lead_days`: default 7 days; `pm_outsourced_lead_days`: default 15 days.
|
||||||
|
- `require_closure_remarks`: default True.
|
||||||
|
- `downtime_milestone`: default `restoration` (downtime terminates when equipment is restored).
|
||||||
|
23. **Alert Recurrence & Notification Re-trigger Policy (§6)**: The alert engine runs daily at 06:00 Asia/Kolkata and employs deterministic deduplication keys (`dedupe_key`) to prevent duplicate in-app notifications on consecutive days while a condition remains active. Overdue alerts escalate in severity to `red`, and an optional repeat reminder interval (`alert_repeat_days`, default 3 days) re-notifies coordinators and biomedical teams until the underlying task (PM, calibration, contract renewal, or breakdown) is addressed. SMTP email dispatch can be enabled in settings when hospital IT confirms mail server credentials.
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
# Poona Hospital AMS — Role-Based User Guide
|
||||||
|
|
||||||
|
Welcome to the Poona Hospital Asset Management & Maintenance System. This quick-start guide details the day-to-day operations, permissions, and typical workflows for each user role.
|
||||||
|
|
||||||
|
All demo accounts share the password: `Demo@123`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. System Administrator (`admin@poona.demo`)
|
||||||
|
|
||||||
|
The System Administrator oversees system security, reference masters, user access, and global configuration.
|
||||||
|
|
||||||
|
### Key Capabilities
|
||||||
|
- **Master Data Management (`/masters`)**: Maintain active Departments, Physical Locations, Equipment Categories, Vendors/Suppliers, and System Users. Masters use soft deletion to preserve historical linkage.
|
||||||
|
- **System Settings (`/settings`)**: Configure hospital-wide business rules:
|
||||||
|
- SLA thresholds (`critical_complaint_sla_hours`, `non_critical_complaint_sla_hours`)
|
||||||
|
- Alert lead times for Contracts, PM, Calibration, Insurance, and Demo Equipment
|
||||||
|
- Mandatory closure remarks toggle (`require_closure_remarks`)
|
||||||
|
- Downtime calculation milestone (`attendance`, `restoration`, or `closure`)
|
||||||
|
- Demo Clock (`demo_as_of_date`) to simulate future dates for testing alerts
|
||||||
|
- **Audit Logs (`/audit-logs`)**: Search, filter, and inspect detailed JSON diffs of all system mutations and user actions.
|
||||||
|
- **Bulk 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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Biomedical Engineer (`bio@poona.demo`)
|
||||||
|
|
||||||
|
Biomedical Engineers handle physical medical assets, breakdown repairs, preventative maintenance schedules, and rounds.
|
||||||
|
|
||||||
|
### Key Workflows
|
||||||
|
- **Asset Registration & Maintenance (`/assets`)**:
|
||||||
|
- Register new medical equipment with full technical, procurement, warranty, and vendor details.
|
||||||
|
- View comprehensive 8-tab overview for any asset (PM, Calibration, Contracts, Insurance, History).
|
||||||
|
- **Breakdown Complaint Management (`/complaints`)**:
|
||||||
|
- Attend assigned complaints and log attendance timestamps.
|
||||||
|
- Document technical actions: Company Engineer (CE) details, action taken, spare parts required, root cause, and corrective action.
|
||||||
|
- Mark equipment as **Restored** when functioning (automatically returning asset to `in_service`).
|
||||||
|
- Close complaints with mandatory closure remarks.
|
||||||
|
- **Preventive Maintenance (`/pm`)**:
|
||||||
|
- View planned PM in Table or 7-column Calendar views.
|
||||||
|
- Execute PM records, attach vendor service reports/job sheets, and automatically advance next planned cycle.
|
||||||
|
- **Department Rounds (`/visits`)**:
|
||||||
|
- Conduct daily/weekly rounds, inspect equipment by department, log observations, note new equipment requirements, and link or spawn breakdown complaints directly from the visit sheet.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Department User (`dept@poona.demo` — ICU)
|
||||||
|
|
||||||
|
Department Users (Nurses, In-charges, Technicians) raise and monitor breakdown calls for their own department.
|
||||||
|
|
||||||
|
### Key Workflows
|
||||||
|
- **Scoped View**: Automatically restricted to seeing only assets and complaints belonging to their assigned department (e.g., ICU).
|
||||||
|
- **Raising Complaints (`/complaints`)**:
|
||||||
|
- Click **Raise Complaint**, search for the faulty equipment using `AssetPicker` (which highlights warranty and condemnation status), choose Priority (`Critical` or `Non-Critical`), and enter the problem description.
|
||||||
|
- Attach photos or fault screenshots directly.
|
||||||
|
- **Tracking Progress**:
|
||||||
|
- Monitor real-time status chips (`Open`, `In Progress`, `Closed`).
|
||||||
|
- View assignment details and attendance timestamps.
|
||||||
|
- Technical engineering fields, spare parts costs, and master configurations are safely locked (read-only).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Management (`mgmt@poona.demo`)
|
||||||
|
|
||||||
|
Hospital Management (Medical Superintendent, Directors, Quality Heads) review operational performance, KPIs, and reports.
|
||||||
|
|
||||||
|
### Key Capabilities
|
||||||
|
- **Hospital Operations Dashboard (`/`)**:
|
||||||
|
- High-level KPI summary: Total Assets, Equipment Under Repair, Open Complaints, Critical Breakdown Calls, and PM Compliance rate.
|
||||||
|
- Interactive charts: Complaints by Status, Complaints by Department, 6-Month Downtime Trend, and PM Performance.
|
||||||
|
- Clickable "Needs Attention" list highlighting urgent overdue items.
|
||||||
|
- **Calibration Plan Approvals (`/calibration`)**:
|
||||||
|
- Review and approve calibration frequencies set on critical biomedical equipment (gated specifically to Management and Administration).
|
||||||
|
- **8 Operational Reports (`/reports`)**:
|
||||||
|
- Monthly Maintenance Summary with downtime minutes and Uptime % calculations.
|
||||||
|
- Monthly Department Performance, PM Compliance, Calibration Due, AMC/CMC Validity, and Breakdown Analytics.
|
||||||
|
- One-click Excel spreadsheet (`.xlsx`) export and print-ready A4 landscape layouts.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Clinical Coordinator (`coord@poona.demo`)
|
||||||
|
|
||||||
|
Coordinators manage legal contracts, equipment warranties, insurance coverage, and loaner/demo devices.
|
||||||
|
|
||||||
|
### Key Workflows
|
||||||
|
- **Contracts & Warranties (`/contracts`)**:
|
||||||
|
- Register AMC and CMC service agreements, coverage periods, and vendor contacts.
|
||||||
|
- Upload signed contract PDFs or warranty certificates.
|
||||||
|
- Renew expiring contracts with automatic superseding of prior contracts and full history chain retention.
|
||||||
|
- **Asset Insurance (`/insurance`)**:
|
||||||
|
- Record policy numbers, insurance companies, coverage sums in INR, and effective dates.
|
||||||
|
- Quick-access **Insurance Drawer** lets users inspect policy details directly from any asset or breakdown record.
|
||||||
|
- **Demo & Trial Equipment (`/demo-equipment`)**:
|
||||||
|
- Track evaluation and trial machines on loan from vendors.
|
||||||
|
- Record serial numbers, trial durations, expected return dates, and log official returns.
|
||||||
|
- **Notifications & Expiry Alerts (`/notifications`)**:
|
||||||
|
- Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies.
|
||||||
@@ -200,6 +200,8 @@ export interface AssetListParams {
|
|||||||
supplier_id?: number;
|
supplier_id?: number;
|
||||||
status?: AssetStatus | "";
|
status?: AssetStatus | "";
|
||||||
criticality?: AssetCriticality | "";
|
criticality?: AssetCriticality | "";
|
||||||
|
requires_calibration?: boolean;
|
||||||
|
insurance_applicable?: boolean;
|
||||||
page?: number;
|
page?: number;
|
||||||
page_size?: number;
|
page_size?: number;
|
||||||
sort?: string;
|
sort?: string;
|
||||||
@@ -264,6 +266,8 @@ export const assetsApi = {
|
|||||||
if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id));
|
if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id));
|
||||||
if (params.status) qs.set("status", params.status);
|
if (params.status) qs.set("status", params.status);
|
||||||
if (params.criticality) qs.set("criticality", params.criticality);
|
if (params.criticality) qs.set("criticality", params.criticality);
|
||||||
|
if (params.requires_calibration !== undefined) qs.set("requires_calibration", String(params.requires_calibration));
|
||||||
|
if (params.insurance_applicable !== undefined) qs.set("insurance_applicable", String(params.insurance_applicable));
|
||||||
qs.set("page", String(params.page ?? 1));
|
qs.set("page", String(params.page ?? 1));
|
||||||
qs.set("page_size", String(params.page_size ?? 200));
|
qs.set("page_size", String(params.page_size ?? 200));
|
||||||
if (params.sort) qs.set("sort", params.sort);
|
if (params.sort) qs.set("sort", params.sort);
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ export type AttachmentEntityType =
|
|||||||
| "insurance"
|
| "insurance"
|
||||||
| "demo_equipment"
|
| "demo_equipment"
|
||||||
| "asset"
|
| "asset"
|
||||||
| "warranty";
|
| "warranty"
|
||||||
|
| "pm_record";
|
||||||
|
|
||||||
export interface AttachmentItem {
|
export interface AttachmentItem {
|
||||||
id: number;
|
id: number;
|
||||||
|
|||||||
@@ -142,4 +142,15 @@ export const calibrationApi = {
|
|||||||
completed_record: CalibrationRecordItem;
|
completed_record: CalibrationRecordItem;
|
||||||
next_record: CalibrationRecordItem;
|
next_record: CalibrationRecordItem;
|
||||||
}>(`/calibration/records/${id}/complete`, data),
|
}>(`/calibration/records/${id}/complete`, data),
|
||||||
|
downloadImportTemplate: async () => {
|
||||||
|
const { blob } = await api.downloadBlob("/calibration/import-template");
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = "calibration_import_template.xlsx";
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ export interface ComplaintItem {
|
|||||||
received_at: string | null;
|
received_at: string | null;
|
||||||
assigned_to_id: number | null;
|
assigned_to_id: number | null;
|
||||||
assigned_to_name: string | null;
|
assigned_to_name: string | null;
|
||||||
|
assigned_team?: string | null;
|
||||||
assigned_at: string | null;
|
assigned_at: string | null;
|
||||||
attended_by_id: number | null;
|
attended_by_id: number | null;
|
||||||
attended_by_name: string | null;
|
attended_by_name: string | null;
|
||||||
@@ -77,6 +78,7 @@ export interface ComplaintEventItem {
|
|||||||
export interface ComplaintListParams {
|
export interface ComplaintListParams {
|
||||||
q?: string;
|
q?: string;
|
||||||
department_id?: number;
|
department_id?: number;
|
||||||
|
location_id?: number;
|
||||||
asset_id?: number;
|
asset_id?: number;
|
||||||
call_status?: CallStatus | "";
|
call_status?: CallStatus | "";
|
||||||
priority?: AssetCriticality | "";
|
priority?: AssetCriticality | "";
|
||||||
@@ -94,6 +96,7 @@ export interface ComplaintCreatePayload {
|
|||||||
breakdown_details?: string | null;
|
breakdown_details?: string | null;
|
||||||
priority: AssetCriticality;
|
priority: AssetCriticality;
|
||||||
notes?: string | null;
|
notes?: string | null;
|
||||||
|
assigned_team?: string | null;
|
||||||
received_by_id?: number | null;
|
received_by_id?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,6 +105,7 @@ export interface ComplaintUpdatePayload {
|
|||||||
breakdown_details?: string | null;
|
breakdown_details?: string | null;
|
||||||
priority?: AssetCriticality;
|
priority?: AssetCriticality;
|
||||||
notes?: string | null;
|
notes?: string | null;
|
||||||
|
assigned_team?: string | null;
|
||||||
action_taken?: string | null;
|
action_taken?: string | null;
|
||||||
root_cause?: string | null;
|
root_cause?: string | null;
|
||||||
corrective_action?: string | null;
|
corrective_action?: string | null;
|
||||||
@@ -119,6 +123,7 @@ export const complaintsApi = {
|
|||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (params.q) qs.set("q", params.q);
|
if (params.q) qs.set("q", params.q);
|
||||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||||
|
if (params.location_id) qs.set("location_id", String(params.location_id));
|
||||||
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
||||||
if (params.call_status) qs.set("call_status", params.call_status);
|
if (params.call_status) qs.set("call_status", params.call_status);
|
||||||
if (params.priority) qs.set("priority", params.priority);
|
if (params.priority) qs.set("priority", params.priority);
|
||||||
@@ -136,7 +141,7 @@ export const complaintsApi = {
|
|||||||
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
|
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
|
||||||
update: (id: number, data: ComplaintUpdatePayload) =>
|
update: (id: number, data: ComplaintUpdatePayload) =>
|
||||||
api.patch<ComplaintItem>(`/complaints/${id}`, data),
|
api.patch<ComplaintItem>(`/complaints/${id}`, data),
|
||||||
assign: (id: number, data: { assigned_to_id: number; note?: string }) =>
|
assign: (id: number, data: { assigned_to_id?: number | null; assigned_team?: string | null; note?: string }) =>
|
||||||
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
|
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
|
||||||
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
|
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
|
||||||
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
|
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
|
||||||
|
|||||||
@@ -141,6 +141,7 @@ export interface DemoEquipmentItem {
|
|||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
equipment_type: string;
|
equipment_type: string;
|
||||||
|
serial_no?: string | null;
|
||||||
supplier_id: number;
|
supplier_id: number;
|
||||||
supplier_name: string | null;
|
supplier_name: string | null;
|
||||||
department_id: number;
|
department_id: number;
|
||||||
@@ -172,6 +173,7 @@ export interface DemoListParams {
|
|||||||
export interface DemoCreatePayload {
|
export interface DemoCreatePayload {
|
||||||
name: string;
|
name: string;
|
||||||
equipment_type: string;
|
equipment_type: string;
|
||||||
|
serial_no?: string | null;
|
||||||
supplier_id: number;
|
supplier_id: number;
|
||||||
department_id: number;
|
department_id: number;
|
||||||
location_id?: number | null;
|
location_id?: number | null;
|
||||||
@@ -202,6 +204,7 @@ export interface VisitItem {
|
|||||||
visited_by_name: string | null;
|
visited_by_name: string | null;
|
||||||
visit_date: string;
|
visit_date: string;
|
||||||
observations: string;
|
observations: string;
|
||||||
|
new_requirements?: string | null;
|
||||||
assets: VisitAssetBrief[];
|
assets: VisitAssetBrief[];
|
||||||
complaints: VisitComplaintBrief[];
|
complaints: VisitComplaintBrief[];
|
||||||
created_at: string;
|
created_at: string;
|
||||||
@@ -221,6 +224,7 @@ export interface VisitCreatePayload {
|
|||||||
department_id: number;
|
department_id: number;
|
||||||
visit_date: string;
|
visit_date: string;
|
||||||
observations: string;
|
observations: string;
|
||||||
|
new_requirements?: string | null;
|
||||||
asset_ids?: number[];
|
asset_ids?: number[];
|
||||||
complaint_ids?: number[];
|
complaint_ids?: number[];
|
||||||
}
|
}
|
||||||
@@ -251,6 +255,17 @@ export const contractsApi = {
|
|||||||
),
|
),
|
||||||
history: (assetId: number) =>
|
history: (assetId: number) =>
|
||||||
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
|
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
|
||||||
|
downloadImportTemplate: async () => {
|
||||||
|
const { blob } = await api.downloadBlob("/contracts/import-template");
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = "contracts_import_template.xlsx";
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const warrantiesApi = {
|
export const warrantiesApi = {
|
||||||
@@ -273,6 +288,17 @@ export const insuranceApi = {
|
|||||||
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
|
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
|
||||||
api.patch<InsuranceItem>(`/insurance/${id}`, data),
|
api.patch<InsuranceItem>(`/insurance/${id}`, data),
|
||||||
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
|
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
|
||||||
|
downloadImportTemplate: async () => {
|
||||||
|
const { blob } = await api.downloadBlob("/insurance/import-template");
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = "insurance_import_template.xlsx";
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const demoEquipmentApi = {
|
export const demoEquipmentApi = {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { ApiError } from "@/api/client";
|
|||||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||||
import { vendorsApi } from "@/api/masters";
|
import { vendorsApi } from "@/api/masters";
|
||||||
import { pmApi, type ServiceMode } from "@/api/pm";
|
import { pmApi, type ServiceMode } from "@/api/pm";
|
||||||
|
import { attachmentsApi } from "@/api/attachments";
|
||||||
|
|
||||||
const inputCls =
|
const inputCls =
|
||||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||||
@@ -250,6 +251,7 @@ export function CompletePMModal({
|
|||||||
const [completedDate, setCompletedDate] = useState("");
|
const [completedDate, setCompletedDate] = useState("");
|
||||||
const [serviceDetails, setServiceDetails] = useState("");
|
const [serviceDetails, setServiceDetails] = useState("");
|
||||||
const [remarks, setRemarks] = useState("");
|
const [remarks, setRemarks] = useState("");
|
||||||
|
const [reportFile, setReportFile] = useState<File | null>(null);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -258,6 +260,7 @@ export function CompletePMModal({
|
|||||||
setCompletedDate(new Date().toISOString().slice(0, 10));
|
setCompletedDate(new Date().toISOString().slice(0, 10));
|
||||||
setServiceDetails("");
|
setServiceDetails("");
|
||||||
setRemarks("");
|
setRemarks("");
|
||||||
|
setReportFile(null);
|
||||||
setError(null);
|
setError(null);
|
||||||
}, [open, recordId]);
|
}, [open, recordId]);
|
||||||
|
|
||||||
@@ -272,8 +275,12 @@ export function CompletePMModal({
|
|||||||
service_details: serviceDetails.trim(),
|
service_details: serviceDetails.trim(),
|
||||||
remarks: remarks.trim() || null,
|
remarks: remarks.trim() || null,
|
||||||
});
|
});
|
||||||
|
if (reportFile) {
|
||||||
|
await attachmentsApi.upload("pm_record", recordId, reportFile);
|
||||||
|
}
|
||||||
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
||||||
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
||||||
|
await qc.invalidateQueries({ queryKey: ["attachments", "pm_record", recordId] });
|
||||||
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||||
onClose();
|
onClose();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -317,6 +324,15 @@ export function CompletePMModal({
|
|||||||
className={inputCls}
|
className={inputCls}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Service Report / Checklist (optional)</label>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept=".pdf,.png,.jpg,.jpeg,.doc,.docx"
|
||||||
|
onChange={(e) => setReportFile(e.target.files?.[0] ?? null)}
|
||||||
|
className="w-full text-xs text-gray-700 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:text-xs file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 border border-gray-200 rounded-md p-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div className="flex justify-end gap-2 pt-2">
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
<Button type="button" variant="outline" onClick={onClose}>
|
<Button type="button" variant="outline" onClick={onClose}>
|
||||||
Cancel
|
Cancel
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ export function AssetsPage() {
|
|||||||
|
|
||||||
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
||||||
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
||||||
|
const [calibrationFilter, setCalibrationFilter] = useState<"all" | "required" | "not_required">("all");
|
||||||
|
const [insuranceFilter, setInsuranceFilter] = useState<"all" | "insured" | "uninsured">("all");
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [bulkOpen, setBulkOpen] = useState(false);
|
const [bulkOpen, setBulkOpen] = useState(false);
|
||||||
|
|
||||||
@@ -44,11 +46,29 @@ export function AssetsPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const assetsQuery = useQuery({
|
const assetsQuery = useQuery({
|
||||||
queryKey: ["assets", selectedDeptId ?? "all", selectedStatus || "all"],
|
queryKey: [
|
||||||
|
"assets",
|
||||||
|
selectedDeptId ?? "all",
|
||||||
|
selectedStatus || "all",
|
||||||
|
calibrationFilter,
|
||||||
|
insuranceFilter,
|
||||||
|
],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
assetsApi.list({
|
assetsApi.list({
|
||||||
department_id: isDeptUser ? undefined : selectedDeptId,
|
department_id: isDeptUser ? undefined : selectedDeptId,
|
||||||
status: selectedStatus || undefined,
|
status: selectedStatus || undefined,
|
||||||
|
requires_calibration:
|
||||||
|
calibrationFilter === "required"
|
||||||
|
? true
|
||||||
|
: calibrationFilter === "not_required"
|
||||||
|
? false
|
||||||
|
: undefined,
|
||||||
|
insurance_applicable:
|
||||||
|
insuranceFilter === "insured"
|
||||||
|
? true
|
||||||
|
: insuranceFilter === "uninsured"
|
||||||
|
? false
|
||||||
|
: undefined,
|
||||||
page_size: 200,
|
page_size: 200,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -208,6 +228,48 @@ export function AssetsPage() {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
|
<span className="text-xs font-medium text-gray-500 mr-1">Calibration:</span>
|
||||||
|
{[
|
||||||
|
{ value: "all", label: "All" },
|
||||||
|
{ value: "required", label: "Calibration Required" },
|
||||||
|
{ value: "not_required", label: "Not Required" },
|
||||||
|
].map((chip) => (
|
||||||
|
<button
|
||||||
|
key={chip.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCalibrationFilter(chip.value as typeof calibrationFilter)}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||||
|
calibrationFilter === chip.value
|
||||||
|
? "bg-emerald-700 text-white"
|
||||||
|
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{chip.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<span className="text-xs font-medium text-gray-500 ml-3 mr-1">Insurance:</span>
|
||||||
|
{[
|
||||||
|
{ value: "all", label: "All" },
|
||||||
|
{ value: "insured", label: "Insurance Applicable" },
|
||||||
|
{ value: "uninsured", label: "Not Applicable" },
|
||||||
|
].map((chip) => (
|
||||||
|
<button
|
||||||
|
key={chip.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setInsuranceFilter(chip.value as typeof insuranceFilter)}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||||
|
insuranceFilter === chip.value
|
||||||
|
? "bg-purple-700 text-white"
|
||||||
|
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{chip.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DataTable
|
<DataTable
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import type { ColumnDef } from "@tanstack/react-table";
|
import type { ColumnDef } from "@tanstack/react-table";
|
||||||
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search } from "lucide-react";
|
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search, Download } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
calibrationApi,
|
calibrationApi,
|
||||||
type CalibrationRecordItem,
|
type CalibrationRecordItem,
|
||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
ApproveCalibrationPlanModal,
|
ApproveCalibrationPlanModal,
|
||||||
CompleteCalibrationModal,
|
CompleteCalibrationModal,
|
||||||
} from "@/components/CalibrationModals";
|
} from "@/components/CalibrationModals";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
|
||||||
type CalTab = "records" | "plans";
|
type CalTab = "records" | "plans";
|
||||||
|
|
||||||
@@ -298,10 +299,26 @@ export function CalibrationPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{canAddCalPlan && (
|
{canAddCalPlan && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
await calibrationApi.downloadImportTemplate();
|
||||||
|
toast.success("Downloaded Calibration import template (.xlsx)");
|
||||||
|
} catch {
|
||||||
|
toast.error("Failed to download template");
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Template (.xlsx)
|
||||||
|
</Button>
|
||||||
<Button onClick={() => setBulkAddOpen(true)}>
|
<Button onClick={() => setBulkAddOpen(true)}>
|
||||||
<Plus className="h-4 w-4 mr-1.5" />
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
Add Equipment to Calibration
|
Add Equipment to Calibration
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ export function ComplaintDetailPage() {
|
|||||||
// Modals
|
// Modals
|
||||||
const [assignOpen, setAssignOpen] = useState(false);
|
const [assignOpen, setAssignOpen] = useState(false);
|
||||||
const [assignUserId, setAssignUserId] = useState<string>("");
|
const [assignUserId, setAssignUserId] = useState<string>("");
|
||||||
|
const [assignTeam, setAssignTeam] = useState<string>("");
|
||||||
const [assignNote, setAssignNote] = useState("");
|
const [assignNote, setAssignNote] = useState("");
|
||||||
|
|
||||||
const [closeOpen, setCloseOpen] = useState(false);
|
const [closeOpen, setCloseOpen] = useState(false);
|
||||||
@@ -173,12 +174,14 @@ export function ComplaintDetailPage() {
|
|||||||
const assignMutation = useMutation({
|
const assignMutation = useMutation({
|
||||||
mutationFn: () =>
|
mutationFn: () =>
|
||||||
complaintsApi.assign(complaintId, {
|
complaintsApi.assign(complaintId, {
|
||||||
assigned_to_id: Number(assignUserId),
|
assigned_to_id: assignUserId ? Number(assignUserId) : undefined,
|
||||||
|
assigned_team: assignTeam.trim() || undefined,
|
||||||
note: assignNote.trim() || undefined,
|
note: assignNote.trim() || undefined,
|
||||||
}),
|
}),
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
setActionError(null);
|
setActionError(null);
|
||||||
setAssignOpen(false);
|
setAssignOpen(false);
|
||||||
|
setAssignTeam("");
|
||||||
setAssignNote("");
|
setAssignNote("");
|
||||||
await refreshAll();
|
await refreshAll();
|
||||||
},
|
},
|
||||||
@@ -432,7 +435,9 @@ export function ComplaintDetailPage() {
|
|||||||
label="Assigned"
|
label="Assigned"
|
||||||
value={
|
value={
|
||||||
c.assigned_to_name
|
c.assigned_to_name
|
||||||
? `${c.assigned_to_name} (${formatDateTime(c.assigned_at)})`
|
? `${c.assigned_to_name}${c.assigned_team ? ` (${c.assigned_team})` : ""} (${formatDateTime(c.assigned_at)})`
|
||||||
|
: c.assigned_team
|
||||||
|
? `Team: ${c.assigned_team} (${formatDateTime(c.assigned_at)})`
|
||||||
: "Unassigned"
|
: "Unassigned"
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -523,6 +528,7 @@ export function ComplaintDetailPage() {
|
|||||||
? String(techUsers[0].id)
|
? String(techUsers[0].id)
|
||||||
: ""
|
: ""
|
||||||
);
|
);
|
||||||
|
setAssignTeam(c.assigned_team ?? "");
|
||||||
setAssignOpen(true);
|
setAssignOpen(true);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -878,6 +884,16 @@ export function ComplaintDetailPage() {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Assigned Team (optional)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="e.g. Biomedical Bio-Eng Team A, Philips CE"
|
||||||
|
value={assignTeam}
|
||||||
|
onChange={(e) => setAssignTeam(e.target.value)}
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className={labelCls}>Note (optional)</label>
|
<label className={labelCls}>Note (optional)</label>
|
||||||
<textarea
|
<textarea
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
type CallStatus,
|
type CallStatus,
|
||||||
} from "@/api/complaints";
|
} from "@/api/complaints";
|
||||||
import type { AssetCriticality } from "@/api/assets";
|
import type { AssetCriticality } from "@/api/assets";
|
||||||
import { departmentsApi, fetchUsersLookup } from "@/api/masters";
|
import { departmentsApi, locationsApi, fetchUsersLookup } from "@/api/masters";
|
||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
import { can } from "@/lib/permissions";
|
import { can } from "@/lib/permissions";
|
||||||
import { formatDateTime, formatDuration } from "@/lib/format";
|
import { formatDateTime, formatDuration } from "@/lib/format";
|
||||||
@@ -35,6 +35,7 @@ export function ComplaintsPage() {
|
|||||||
|
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const [departmentId, setDepartmentId] = useState<string>("");
|
const [departmentId, setDepartmentId] = useState<string>("");
|
||||||
|
const [locationId, setLocationId] = useState<string>("");
|
||||||
const [callStatus, setCallStatus] = useState<CallStatus | "">("");
|
const [callStatus, setCallStatus] = useState<CallStatus | "">("");
|
||||||
const [priority, setPriority] = useState<AssetCriticality | "">("");
|
const [priority, setPriority] = useState<AssetCriticality | "">("");
|
||||||
const [assignedToId, setAssignedToId] = useState<string>("");
|
const [assignedToId, setAssignedToId] = useState<string>("");
|
||||||
@@ -49,6 +50,11 @@ export function ComplaintsPage() {
|
|||||||
enabled: !isDeptUser,
|
enabled: !isDeptUser,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const locationsQuery = useQuery({
|
||||||
|
queryKey: ["locations", "active-only"],
|
||||||
|
queryFn: () => locationsApi.list(false),
|
||||||
|
});
|
||||||
|
|
||||||
const usersQuery = useQuery({
|
const usersQuery = useQuery({
|
||||||
queryKey: ["users-lookup"],
|
queryKey: ["users-lookup"],
|
||||||
queryFn: fetchUsersLookup,
|
queryFn: fetchUsersLookup,
|
||||||
@@ -59,6 +65,7 @@ export function ComplaintsPage() {
|
|||||||
"complaints",
|
"complaints",
|
||||||
q,
|
q,
|
||||||
departmentId,
|
departmentId,
|
||||||
|
locationId,
|
||||||
callStatus,
|
callStatus,
|
||||||
priority,
|
priority,
|
||||||
assignedToId,
|
assignedToId,
|
||||||
@@ -70,6 +77,7 @@ export function ComplaintsPage() {
|
|||||||
complaintsApi.list({
|
complaintsApi.list({
|
||||||
q: q.trim() || undefined,
|
q: q.trim() || undefined,
|
||||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||||
|
location_id: locationId ? Number(locationId) : undefined,
|
||||||
call_status: callStatus || undefined,
|
call_status: callStatus || undefined,
|
||||||
priority: priority || undefined,
|
priority: priority || undefined,
|
||||||
assigned_to_id: assignedToId ? Number(assignedToId) : undefined,
|
assigned_to_id: assignedToId ? Number(assignedToId) : undefined,
|
||||||
@@ -177,6 +185,10 @@ export function ComplaintsPage() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const departments = deptsQuery.data?.items ?? [];
|
const departments = deptsQuery.data?.items ?? [];
|
||||||
|
const allLocations = locationsQuery.data?.items ?? [];
|
||||||
|
const filteredLocations = departmentId
|
||||||
|
? allLocations.filter((l) => l.department_id === Number(departmentId))
|
||||||
|
: allLocations;
|
||||||
const techUsers = (usersQuery.data?.items ?? []).filter(
|
const techUsers = (usersQuery.data?.items ?? []).filter(
|
||||||
(u) => u.role === "biomedical" || u.role === "system_admin"
|
(u) => u.role === "biomedical" || u.role === "system_admin"
|
||||||
);
|
);
|
||||||
@@ -235,7 +247,10 @@ export function ComplaintsPage() {
|
|||||||
{!isDeptUser && (
|
{!isDeptUser && (
|
||||||
<select
|
<select
|
||||||
value={departmentId}
|
value={departmentId}
|
||||||
onChange={(e) => setDepartmentId(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setDepartmentId(e.target.value);
|
||||||
|
setLocationId("");
|
||||||
|
}}
|
||||||
aria-label="Filter by Department"
|
aria-label="Filter by Department"
|
||||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
>
|
>
|
||||||
@@ -248,6 +263,20 @@ export function ComplaintsPage() {
|
|||||||
</select>
|
</select>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<select
|
||||||
|
value={locationId}
|
||||||
|
onChange={(e) => setLocationId(e.target.value)}
|
||||||
|
aria-label="Filter by Location"
|
||||||
|
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
>
|
||||||
|
<option value="">All Locations</option>
|
||||||
|
{filteredLocations.map((loc) => (
|
||||||
|
<option key={loc.id} value={String(loc.id)}>
|
||||||
|
{loc.name} {loc.floor_wing ? `(${loc.floor_wing})` : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
<select
|
<select
|
||||||
value={priority}
|
value={priority}
|
||||||
onChange={(e) => setPriority(e.target.value as AssetCriticality | "")}
|
onChange={(e) => setPriority(e.target.value as AssetCriticality | "")}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
Search,
|
Search,
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
|
Download,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import {
|
import {
|
||||||
contractsApi,
|
contractsApi,
|
||||||
@@ -469,6 +470,23 @@ export function ContractsPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{canManage && (
|
{canManage && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{tab === "contracts" && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
await contractsApi.downloadImportTemplate();
|
||||||
|
toast.success("Downloaded Contract import template (.xlsx)");
|
||||||
|
} catch {
|
||||||
|
toast.error("Failed to download template");
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Template (.xlsx)
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (tab === "contracts") {
|
if (tab === "contracts") {
|
||||||
@@ -483,6 +501,7 @@ export function ContractsPage() {
|
|||||||
<Plus className="h-4 w-4 mr-1.5" />
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
{tab === "contracts" ? "Add Contract" : "Add Warranty"}
|
{tab === "contracts" ? "Add Contract" : "Add Warranty"}
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -119,14 +119,19 @@ export function DemoEquipmentPage() {
|
|||||||
const columns: ColumnDef<DemoEquipmentItem, unknown>[] = [
|
const columns: ColumnDef<DemoEquipmentItem, unknown>[] = [
|
||||||
{
|
{
|
||||||
id: "equipment",
|
id: "equipment",
|
||||||
accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""}`,
|
accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""} ${r.serial_no ?? ""}`,
|
||||||
header: "Equipment",
|
header: "Equipment",
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<div>
|
<div>
|
||||||
<div className="font-medium text-gray-900">{row.original.name}</div>
|
<div className="font-medium text-gray-900">{row.original.name}</div>
|
||||||
{row.original.equipment_type && (
|
<div className="text-xs text-gray-500">
|
||||||
<div className="text-xs text-gray-500">{row.original.equipment_type}</div>
|
{[
|
||||||
)}
|
row.original.equipment_type,
|
||||||
|
row.original.serial_no ? `SN: ${row.original.serial_no}` : null,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" • ")}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -428,6 +433,7 @@ function DemoFormModal({
|
|||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [equipmentType, setEquipmentType] = useState("");
|
const [equipmentType, setEquipmentType] = useState("");
|
||||||
|
const [serialNo, setSerialNo] = useState("");
|
||||||
const [supplierId, setSupplierId] = useState("");
|
const [supplierId, setSupplierId] = useState("");
|
||||||
const [departmentId, setDepartmentId] = useState("");
|
const [departmentId, setDepartmentId] = useState("");
|
||||||
const [locationId, setLocationId] = useState("");
|
const [locationId, setLocationId] = useState("");
|
||||||
@@ -443,6 +449,7 @@ function DemoFormModal({
|
|||||||
if (editing) {
|
if (editing) {
|
||||||
setName(editing.name);
|
setName(editing.name);
|
||||||
setEquipmentType(editing.equipment_type ?? "");
|
setEquipmentType(editing.equipment_type ?? "");
|
||||||
|
setSerialNo(editing.serial_no ?? "");
|
||||||
setSupplierId(String(editing.supplier_id));
|
setSupplierId(String(editing.supplier_id));
|
||||||
setDepartmentId(String(editing.department_id));
|
setDepartmentId(String(editing.department_id));
|
||||||
setLocationId(editing.location_id ? String(editing.location_id) : "");
|
setLocationId(editing.location_id ? String(editing.location_id) : "");
|
||||||
@@ -455,6 +462,7 @@ function DemoFormModal({
|
|||||||
plus14.setDate(plus14.getDate() + 14);
|
plus14.setDate(plus14.getDate() + 14);
|
||||||
setName("");
|
setName("");
|
||||||
setEquipmentType("");
|
setEquipmentType("");
|
||||||
|
setSerialNo("");
|
||||||
setSupplierId("");
|
setSupplierId("");
|
||||||
setDepartmentId("");
|
setDepartmentId("");
|
||||||
setLocationId("");
|
setLocationId("");
|
||||||
@@ -476,6 +484,7 @@ function DemoFormModal({
|
|||||||
const payload = {
|
const payload = {
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
equipment_type: equipmentType.trim(),
|
equipment_type: equipmentType.trim(),
|
||||||
|
serial_no: serialNo.trim() || null,
|
||||||
supplier_id: Number(supplierId),
|
supplier_id: Number(supplierId),
|
||||||
department_id: Number(departmentId),
|
department_id: Number(departmentId),
|
||||||
location_id: locationId ? Number(locationId) : null,
|
location_id: locationId ? Number(locationId) : null,
|
||||||
@@ -537,6 +546,16 @@ function DemoFormModal({
|
|||||||
className={inputCls}
|
className={inputCls}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Serial Number</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={serialNo}
|
||||||
|
onChange={(e) => setSerialNo(e.target.value)}
|
||||||
|
placeholder="e.g. SN-DEMO-901"
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className={labelCls}>Supplier *</label>
|
<label className={labelCls}>Supplier *</label>
|
||||||
<select
|
<select
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
Search,
|
Search,
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
|
Download,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
||||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||||
@@ -238,6 +239,21 @@ export function InsurancePage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{canManage && (
|
{canManage && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
await insuranceApi.downloadImportTemplate();
|
||||||
|
toast.success("Downloaded Insurance import template (.xlsx)");
|
||||||
|
} catch {
|
||||||
|
toast.error("Failed to download template");
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Template (.xlsx)
|
||||||
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
@@ -247,6 +263,7 @@ export function InsurancePage() {
|
|||||||
<Plus className="h-4 w-4 mr-1.5" />
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
Add Insurance Policy
|
Add Insurance Policy
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Search,
|
Search,
|
||||||
|
Paperclip,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import {
|
import {
|
||||||
pmApi,
|
pmApi,
|
||||||
@@ -28,6 +29,7 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Modal } from "@/components/ui/dialog";
|
import { Modal } from "@/components/ui/dialog";
|
||||||
import { ScheduleStatusBadge } from "@/components/StatusBadge";
|
import { ScheduleStatusBadge } from "@/components/StatusBadge";
|
||||||
|
import { Attachments } from "@/components/Attachments";
|
||||||
import {
|
import {
|
||||||
NewPMScheduleModal,
|
NewPMScheduleModal,
|
||||||
CompletePMModal,
|
CompletePMModal,
|
||||||
@@ -96,6 +98,7 @@ export function PMPage() {
|
|||||||
const [completingRec, setCompletingRec] = useState<PMRecordItem | null>(null);
|
const [completingRec, setCompletingRec] = useState<PMRecordItem | null>(null);
|
||||||
const [reschedulingRec, setReschedulingRec] = useState<PMRecordItem | null>(null);
|
const [reschedulingRec, setReschedulingRec] = useState<PMRecordItem | null>(null);
|
||||||
const [calendarDetailRec, setCalendarDetailRec] = useState<PMRecordItem | null>(null);
|
const [calendarDetailRec, setCalendarDetailRec] = useState<PMRecordItem | null>(null);
|
||||||
|
const [attachRec, setAttachRec] = useState<PMRecordItem | null>(null);
|
||||||
|
|
||||||
const effectiveCalendarMonth = monthFilter || currentYearMonth();
|
const effectiveCalendarMonth = monthFilter || currentYearMonth();
|
||||||
|
|
||||||
@@ -236,6 +239,23 @@ export function PMPage() {
|
|||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "attachments",
|
||||||
|
header: "Reports",
|
||||||
|
enableSorting: false,
|
||||||
|
enableColumnFilter: false,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setAttachRec(row.original)}
|
||||||
|
aria-label={`Attachments for PM ${row.original.id}`}
|
||||||
|
>
|
||||||
|
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Docs
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
},
|
||||||
...(canManagePm
|
...(canManagePm
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
@@ -726,6 +746,21 @@ export function PMPage() {
|
|||||||
}
|
}
|
||||||
assetId={reschedulingRec?.asset_id}
|
assetId={reschedulingRec?.asset_id}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{attachRec && (
|
||||||
|
<Modal
|
||||||
|
open={Boolean(attachRec)}
|
||||||
|
onOpenChange={(o) => !o && setAttachRec(null)}
|
||||||
|
title={`PM Service Reports — ${attachRec.asset_code} (${attachRec.asset_name})`}
|
||||||
|
>
|
||||||
|
<Attachments
|
||||||
|
entityType="pm_record"
|
||||||
|
entityId={attachRec.id}
|
||||||
|
canUpload={canManagePm}
|
||||||
|
canDelete={canManagePm}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -106,11 +106,16 @@ export function VisitsPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "observations",
|
accessorKey: "observations",
|
||||||
header: "Observations",
|
header: "Observations & Requirements",
|
||||||
cell: ({ getValue }) => (
|
cell: ({ row }) => (
|
||||||
<p className="text-xs text-gray-800 whitespace-pre-wrap max-w-sm">
|
<div className="space-y-1 max-w-sm">
|
||||||
{String(getValue())}
|
<p className="text-xs text-gray-800 whitespace-pre-wrap">{row.original.observations}</p>
|
||||||
|
{row.original.new_requirements && (
|
||||||
|
<p className="text-xs text-blue-700 bg-blue-50 border border-blue-100 rounded px-1.5 py-0.5">
|
||||||
|
<span className="font-semibold">Requirements:</span> {row.original.new_requirements}
|
||||||
</p>
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -292,6 +297,7 @@ function VisitFormModal({
|
|||||||
const [departmentId, setDepartmentId] = useState("");
|
const [departmentId, setDepartmentId] = useState("");
|
||||||
const [visitDate, setVisitDate] = useState("");
|
const [visitDate, setVisitDate] = useState("");
|
||||||
const [observations, setObservations] = useState("");
|
const [observations, setObservations] = useState("");
|
||||||
|
const [newRequirements, setNewRequirements] = useState("");
|
||||||
const [selectedAssetIds, setSelectedAssetIds] = useState<number[]>([]);
|
const [selectedAssetIds, setSelectedAssetIds] = useState<number[]>([]);
|
||||||
const [assetSearch, setAssetSearch] = useState("");
|
const [assetSearch, setAssetSearch] = useState("");
|
||||||
const [raiseImmediately, setRaiseImmediately] = useState(false);
|
const [raiseImmediately, setRaiseImmediately] = useState(false);
|
||||||
@@ -307,11 +313,13 @@ function VisitFormModal({
|
|||||||
setDepartmentId(String(editing.department_id));
|
setDepartmentId(String(editing.department_id));
|
||||||
setVisitDate(editing.visit_date);
|
setVisitDate(editing.visit_date);
|
||||||
setObservations(editing.observations);
|
setObservations(editing.observations);
|
||||||
|
setNewRequirements(editing.new_requirements ?? "");
|
||||||
setSelectedAssetIds(editing.assets.map((a) => a.id));
|
setSelectedAssetIds(editing.assets.map((a) => a.id));
|
||||||
} else {
|
} else {
|
||||||
setDepartmentId("");
|
setDepartmentId("");
|
||||||
setVisitDate(new Date().toISOString().slice(0, 10));
|
setVisitDate(new Date().toISOString().slice(0, 10));
|
||||||
setObservations("");
|
setObservations("");
|
||||||
|
setNewRequirements("");
|
||||||
setSelectedAssetIds([]);
|
setSelectedAssetIds([]);
|
||||||
}
|
}
|
||||||
}, [open, editing]);
|
}, [open, editing]);
|
||||||
@@ -357,6 +365,7 @@ function VisitFormModal({
|
|||||||
department_id: Number(departmentId),
|
department_id: Number(departmentId),
|
||||||
visit_date: visitDate,
|
visit_date: visitDate,
|
||||||
observations: observations.trim(),
|
observations: observations.trim(),
|
||||||
|
new_requirements: newRequirements.trim() || null,
|
||||||
asset_ids: selectedAssetIds,
|
asset_ids: selectedAssetIds,
|
||||||
});
|
});
|
||||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||||
@@ -366,6 +375,7 @@ function VisitFormModal({
|
|||||||
department_id: Number(departmentId),
|
department_id: Number(departmentId),
|
||||||
visit_date: visitDate,
|
visit_date: visitDate,
|
||||||
observations: observations.trim(),
|
observations: observations.trim(),
|
||||||
|
new_requirements: newRequirements.trim() || null,
|
||||||
asset_ids: selectedAssetIds,
|
asset_ids: selectedAssetIds,
|
||||||
});
|
});
|
||||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||||
@@ -498,6 +508,17 @@ function VisitFormModal({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>New Equipment / Maintenance Requirements</label>
|
||||||
|
<textarea
|
||||||
|
rows={2}
|
||||||
|
value={newRequirements}
|
||||||
|
onChange={(e) => setNewRequirements(e.target.value)}
|
||||||
|
placeholder="e.g. Additional infusion pumps requested, new mounting brackets needed..."
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{!editing && (
|
{!editing && (
|
||||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||||
<input
|
<input
|
||||||
|
|||||||
Reference in New Issue
Block a user