feat: complete requirements gaps - backup/restore, uat signoff, pm attachments, templates, and filters
This commit is contained in:
@@ -21,6 +21,7 @@ class Complaint(Base):
|
||||
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
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_team: Mapped[Optional[str]] = mapped_column(String(100), 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_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)
|
||||
name: Mapped[str] = mapped_column(String(200), 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)
|
||||
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)
|
||||
@@ -52,6 +53,7 @@ class DepartmentVisit(Base):
|
||||
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
||||
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_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)
|
||||
|
||||
@@ -371,6 +371,8 @@ def list_assets(
|
||||
supplier_id: Optional[int] = None,
|
||||
status_filter: Optional[str] = Query(None, alias="status"),
|
||||
criticality: Optional[str] = None,
|
||||
requires_calibration: Optional[bool] = None,
|
||||
insurance_applicable: Optional[bool] = None,
|
||||
warranty_status: Optional[str] = None,
|
||||
contract_status: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
@@ -401,6 +403,10 @@ def list_assets(
|
||||
query = query.filter(Asset.status == status_filter)
|
||||
if 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():
|
||||
like = f"%{q.strip()}%"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
@@ -25,6 +26,7 @@ from ..schemas.calibration import (
|
||||
CalibrationStatusFilter,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_calibration_template_xlsx
|
||||
from ..services.calculations import compute_schedule_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
@@ -196,6 +198,19 @@ def _create_plan_and_initial_record(
|
||||
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)
|
||||
def list_calibration_plans(
|
||||
q: str = "",
|
||||
|
||||
@@ -144,6 +144,7 @@ def _to_complaint_out(
|
||||
received_at=recv_at,
|
||||
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_team=c.assigned_team,
|
||||
assigned_at=asg_at,
|
||||
attended_by_id=c.attended_by_id,
|
||||
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(
|
||||
q: Optional[str] = None,
|
||||
department_id: Optional[int] = None,
|
||||
location_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
call_status: Optional[str] = None,
|
||||
priority: Optional[str] = None,
|
||||
@@ -260,6 +262,9 @@ def list_complaints(
|
||||
elif department_id is not None:
|
||||
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:
|
||||
query = query.filter(Complaint.asset_id == asset_id)
|
||||
if call_status:
|
||||
@@ -372,6 +377,7 @@ def create_complaint(
|
||||
breakdown_details=payload.breakdown_details,
|
||||
priority=payload.priority,
|
||||
notes=payload.notes,
|
||||
assigned_team=payload.assigned_team,
|
||||
registered_at=reg_at,
|
||||
registered_by_id=current_user.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)),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
|
||||
if assignee is None:
|
||||
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
|
||||
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()
|
||||
if assignee is None:
|
||||
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
|
||||
target_name = assignee.name
|
||||
if payload.assigned_team:
|
||||
target_name = f"{assignee.name} ({payload.assigned_team})"
|
||||
|
||||
old_name: Optional[str] = None
|
||||
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"
|
||||
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
|
||||
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
|
||||
if comp.assigned_to_id is not None:
|
||||
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
|
||||
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
|
||||
if comp.assigned_team:
|
||||
old_name = f"{old_name} ({comp.assigned_team})" if old_name else comp.assigned_team
|
||||
|
||||
now = utc_now()
|
||||
comp.assigned_to_id = assignee.id
|
||||
if assignee:
|
||||
comp.assigned_to_id = assignee.id
|
||||
if payload.assigned_team is not None:
|
||||
comp.assigned_team = payload.assigned_team.strip() or None
|
||||
comp.assigned_at = now
|
||||
if comp.call_status == "open":
|
||||
comp.call_status = "in_progress"
|
||||
@@ -578,7 +599,7 @@ def assign_complaint(
|
||||
complaint_id=comp.id,
|
||||
event_type=event_type,
|
||||
from_value=old_name,
|
||||
to_value=assignee.name,
|
||||
to_value=target_name,
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=payload.note,
|
||||
@@ -589,7 +610,11 @@ def assign_complaint(
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
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,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
@@ -21,6 +22,7 @@ from ..schemas.contracts import (
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_contracts_template_xlsx
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
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)
|
||||
def create_contract(
|
||||
payload: ContractCreate,
|
||||
|
||||
@@ -48,6 +48,7 @@ def _to_demo_out(
|
||||
id=item.id,
|
||||
name=item.name,
|
||||
equipment_type=item.equipment_type,
|
||||
serial_no=item.serial_no,
|
||||
supplier_id=item.supplier_id,
|
||||
supplier_name=item.supplier.name if item.supplier else None,
|
||||
department_id=item.department_id,
|
||||
@@ -160,6 +161,7 @@ def create_demo_equipment(
|
||||
item = DemoEquipment(
|
||||
name=payload.name.strip(),
|
||||
equipment_type=payload.equipment_type.strip(),
|
||||
serial_no=payload.serial_no.strip() if payload.serial_no else None,
|
||||
supplier_id=payload.supplier_id,
|
||||
department_id=payload.department_id,
|
||||
location_id=payload.location_id,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
@@ -17,6 +18,7 @@ from ..schemas.insurance import (
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_insurance_template_xlsx
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
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)
|
||||
|
||||
|
||||
@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)
|
||||
def create_insurance_policy(
|
||||
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,
|
||||
visit_date=v.visit_date,
|
||||
observations=v.observations,
|
||||
new_requirements=v.new_requirements,
|
||||
assets=[
|
||||
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
|
||||
for a in v.assets
|
||||
@@ -198,6 +199,7 @@ def create_visit(
|
||||
visited_by_id=visited_by_id,
|
||||
visit_date=payload.visit_date,
|
||||
observations=clean_obs,
|
||||
new_requirements=payload.new_requirements.strip() if payload.new_requirements else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
@@ -254,6 +256,9 @@ def update_visit(
|
||||
detail="observations cannot be blank.",
|
||||
)
|
||||
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(
|
||||
db,
|
||||
|
||||
@@ -19,6 +19,7 @@ class ComplaintCreate(BaseModel):
|
||||
breakdown_details: Optional[str] = None
|
||||
priority: ComplaintPriority = "non_critical"
|
||||
notes: Optional[str] = None
|
||||
assigned_team: Optional[str] = None
|
||||
received_by_id: Optional[int] = None
|
||||
received_at: Optional[datetime] = None
|
||||
|
||||
@@ -28,6 +29,7 @@ class ComplaintUpdate(BaseModel):
|
||||
breakdown_details: Optional[str] = None
|
||||
priority: Optional[ComplaintPriority] = None
|
||||
notes: Optional[str] = None
|
||||
assigned_team: Optional[str] = None
|
||||
closure_remarks: Optional[str] = None
|
||||
# Restricted technical fields (system_admin / biomedical only)
|
||||
action_taken: Optional[str] = None
|
||||
@@ -43,7 +45,8 @@ class ComplaintUpdate(BaseModel):
|
||||
|
||||
|
||||
class ComplaintAssignIn(BaseModel):
|
||||
assigned_to_id: int
|
||||
assigned_to_id: Optional[int] = None
|
||||
assigned_team: Optional[str] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
@@ -94,6 +97,7 @@ class ComplaintOut(BaseModel):
|
||||
received_at: Optional[datetime] = None
|
||||
assigned_to_id: Optional[int] = None
|
||||
assigned_to_name: Optional[str] = None
|
||||
assigned_team: Optional[str] = None
|
||||
assigned_at: Optional[datetime] = None
|
||||
attended_by_id: Optional[int] = None
|
||||
attended_by_name: Optional[str] = None
|
||||
|
||||
@@ -8,6 +8,7 @@ DemoStatusFilter = Literal["on_demo", "overdue_return", "returned"]
|
||||
class DemoEquipmentCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
equipment_type: str = Field(..., min_length=1)
|
||||
serial_no: Optional[str] = None
|
||||
supplier_id: int
|
||||
department_id: int
|
||||
location_id: Optional[int] = None
|
||||
@@ -19,6 +20,7 @@ class DemoEquipmentCreate(BaseModel):
|
||||
class DemoEquipmentUpdate(BaseModel):
|
||||
name: 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
|
||||
department_id: Optional[int] = None
|
||||
location_id: Optional[int] = None
|
||||
@@ -39,6 +41,7 @@ class DemoEquipmentOut(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
equipment_type: str
|
||||
serial_no: Optional[str] = None
|
||||
supplier_id: int
|
||||
supplier_name: Optional[str] = None
|
||||
department_id: int
|
||||
|
||||
@@ -21,6 +21,7 @@ class VisitCreate(BaseModel):
|
||||
department_id: int
|
||||
visit_date: date
|
||||
observations: str = Field(..., min_length=1)
|
||||
new_requirements: Optional[str] = None
|
||||
asset_ids: list[int] = Field(default_factory=list)
|
||||
complaint_ids: list[int] = Field(default_factory=list)
|
||||
visited_by_id: Optional[int] = None
|
||||
@@ -30,6 +31,7 @@ class VisitUpdate(BaseModel):
|
||||
department_id: Optional[int] = None
|
||||
visit_date: Optional[date] = None
|
||||
observations: Optional[str] = Field(None, min_length=1)
|
||||
new_requirements: Optional[str] = None
|
||||
asset_ids: Optional[list[int]] = None
|
||||
complaint_ids: Optional[list[int]] = None
|
||||
|
||||
@@ -48,6 +50,7 @@ class VisitOut(BaseModel):
|
||||
visited_by_name: Optional[str] = None
|
||||
visit_date: date
|
||||
observations: Optional[str] = None
|
||||
new_requirements: Optional[str] = None
|
||||
assets: list[VisitAssetSummary] = Field(default_factory=list)
|
||||
complaints: list[VisitComplaintSummary] = Field(default_factory=list)
|
||||
created_at: datetime
|
||||
|
||||
@@ -15,6 +15,8 @@ from ..models import (
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
InsurancePolicy,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Warranty,
|
||||
)
|
||||
@@ -29,6 +31,7 @@ ALLOWED_ENTITY_TYPES: set[str] = {
|
||||
"demo_equipment",
|
||||
"asset",
|
||||
"warranty",
|
||||
"pm_record",
|
||||
}
|
||||
|
||||
EXT_TO_MIME: dict[str, str] = {
|
||||
@@ -50,6 +53,7 @@ COORDINATOR_UPLOAD_ENTITIES: set[str] = {
|
||||
"insurance",
|
||||
"warranty",
|
||||
"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")
|
||||
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")
|
||||
|
||||
|
||||
|
||||
@@ -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_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]
|
||||
notes = "; ".join(
|
||||
obs_notes = "; ".join(
|
||||
f"[{format_date(v.visit_date)}] {v.observations.strip()}"
|
||||
for v in d_visits
|
||||
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(
|
||||
{
|
||||
"department_id": d.id,
|
||||
@@ -278,7 +283,8 @@ def _build_monthly_department(
|
||||
"outstanding_complaints_count": len(d_cmps),
|
||||
"critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"),
|
||||
"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": "critical_open_count", "label": "Critical Open"},
|
||||
{"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,
|
||||
}
|
||||
|
||||
@@ -237,6 +237,56 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
|
||||
"max": 24,
|
||||
"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}
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user