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}
|
||||
|
||||
Reference in New Issue
Block a user