phase-5: contracts, warranties, insurance, demo equipment, and department visits
This commit is contained in:
+22
-1
@@ -7,7 +7,23 @@ from fastapi.responses import JSONResponse
|
||||
from .core.db import SessionLocal, engine
|
||||
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
||||
from .models import Base
|
||||
from .routers import assets, attachments, auth, calibration, complaints, health, masters, pm, settings, users
|
||||
from .routers import (
|
||||
assets,
|
||||
attachments,
|
||||
auth,
|
||||
calibration,
|
||||
complaints,
|
||||
contracts,
|
||||
demo_equipment,
|
||||
health,
|
||||
insurance,
|
||||
masters,
|
||||
pm,
|
||||
settings,
|
||||
users,
|
||||
visits,
|
||||
warranties,
|
||||
)
|
||||
from .services.settings_service import ensure_default_settings
|
||||
|
||||
logging.basicConfig(
|
||||
@@ -65,3 +81,8 @@ app.include_router(attachments.router, prefix="/api")
|
||||
app.include_router(complaints.router, prefix="/api")
|
||||
app.include_router(pm.router, prefix="/api")
|
||||
app.include_router(calibration.router, prefix="/api")
|
||||
app.include_router(contracts.router, prefix="/api")
|
||||
app.include_router(warranties.router, prefix="/api")
|
||||
app.include_router(insurance.router, prefix="/api")
|
||||
app.include_router(demo_equipment.router, prefix="/api")
|
||||
app.include_router(visits.router, prefix="/api")
|
||||
|
||||
@@ -58,5 +58,6 @@ class DepartmentVisit(Base):
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
|
||||
department = relationship("Department")
|
||||
visited_by = relationship("User", foreign_keys=[visited_by_id])
|
||||
assets = relationship("Asset", secondary=department_visit_assets)
|
||||
complaints = relationship("Complaint", secondary=department_visit_complaints)
|
||||
|
||||
@@ -1,4 +1,20 @@
|
||||
from . import assets, attachments, auth, calibration, complaints, health, masters, pm, settings, users
|
||||
from . import (
|
||||
assets,
|
||||
attachments,
|
||||
auth,
|
||||
calibration,
|
||||
complaints,
|
||||
contracts,
|
||||
demo_equipment,
|
||||
health,
|
||||
insurance,
|
||||
masters,
|
||||
pm,
|
||||
settings,
|
||||
users,
|
||||
visits,
|
||||
warranties,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"assets",
|
||||
@@ -6,9 +22,14 @@ __all__ = [
|
||||
"auth",
|
||||
"calibration",
|
||||
"complaints",
|
||||
"contracts",
|
||||
"demo_equipment",
|
||||
"health",
|
||||
"insurance",
|
||||
"masters",
|
||||
"pm",
|
||||
"settings",
|
||||
"users",
|
||||
"visits",
|
||||
"warranties",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models import Asset, Contract, PMSchedule, User, Vendor
|
||||
from ..schemas.contracts import (
|
||||
ContractCreate,
|
||||
ContractHistoryOut,
|
||||
ContractListOut,
|
||||
ContractOut,
|
||||
ContractRenewIn,
|
||||
ContractRenewOut,
|
||||
ContractStatusFilter,
|
||||
ContractType,
|
||||
ContractUpdate,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/contracts", tags=["contracts"])
|
||||
|
||||
|
||||
def _contract_lead_settings(db: Session) -> tuple[int, int]:
|
||||
lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"amc_cmc_lead_days",
|
||||
get_setting_value(db, "contract_expiry_alert_days", 30),
|
||||
)
|
||||
)
|
||||
red = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
return lead, red
|
||||
|
||||
|
||||
def _to_contract_out(
|
||||
c: Contract,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> ContractOut:
|
||||
asset = c.asset
|
||||
if c.is_superseded:
|
||||
st, sev = "superseded", "ok"
|
||||
else:
|
||||
st, sev = coverage_status(c.start_date, c.end_date, today, lead_days, red_days)
|
||||
return ContractOut(
|
||||
id=c.id,
|
||||
asset_id=c.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
contract_type=c.contract_type,
|
||||
provider_id=c.provider_id,
|
||||
provider_name=c.provider.name if c.provider else None,
|
||||
start_date=c.start_date,
|
||||
end_date=c.end_date,
|
||||
coverage_period_text=c.coverage_period_text,
|
||||
renewed_from_id=c.renewed_from_id,
|
||||
is_superseded=c.is_superseded,
|
||||
status=st,
|
||||
severity=sev,
|
||||
days_to_expiry=(c.end_date - today).days,
|
||||
attachment_count=att_counts.get(c.id, 0),
|
||||
remarks=c.remarks,
|
||||
created_at=c.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_contract(db: Session, contract_id: int) -> Contract | None:
|
||||
return (
|
||||
db.query(Contract)
|
||||
.options(
|
||||
joinedload(Contract.asset).joinedload(Asset.department),
|
||||
joinedload(Contract.provider),
|
||||
)
|
||||
.filter(Contract.id == contract_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=ContractListOut)
|
||||
def list_contracts(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
provider_id: Optional[int] = None,
|
||||
contract_type: Optional[ContractType] = None,
|
||||
status_filter: Optional[ContractStatusFilter] = Query(None, alias="status"),
|
||||
include_superseded: bool = True,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(Contract)
|
||||
.join(Asset, Contract.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, Contract.provider_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(Contract.asset).joinedload(Asset.department),
|
||||
joinedload(Contract.provider),
|
||||
)
|
||||
)
|
||||
if current_user.role == Role.department_user.value:
|
||||
query = query.filter(Asset.department_id == current_user.department_id)
|
||||
elif department_id is not None:
|
||||
query = query.filter(Asset.department_id == department_id)
|
||||
|
||||
if asset_id is not None:
|
||||
query = query.filter(Contract.asset_id == asset_id)
|
||||
if provider_id is not None:
|
||||
query = query.filter(Contract.provider_id == provider_id)
|
||||
if contract_type is not None:
|
||||
query = query.filter(Contract.contract_type == contract_type)
|
||||
if not include_superseded:
|
||||
query = query.filter(Contract.is_superseded.is_(False))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
Contract.coverage_period_text.ilike(like),
|
||||
Contract.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(Contract.is_superseded.asc(), Contract.end_date.asc(), Contract.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
|
||||
items_all = [_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return ContractListOut(items=items_all[start : start + page_size], total=total)
|
||||
|
||||
|
||||
@router.get("/history/{asset_id}", response_model=ContractHistoryOut)
|
||||
def get_contract_history(
|
||||
asset_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
asset = db.query(Asset).filter(Asset.id == asset_id).first()
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied for another department's asset.")
|
||||
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
rows = (
|
||||
db.query(Contract)
|
||||
.options(
|
||||
joinedload(Contract.asset).joinedload(Asset.department),
|
||||
joinedload(Contract.provider),
|
||||
)
|
||||
.filter(Contract.asset_id == asset_id)
|
||||
.order_by(Contract.start_date.desc(), Contract.id.desc())
|
||||
.all()
|
||||
)
|
||||
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
|
||||
return ContractHistoryOut(
|
||||
items=[_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_contract(
|
||||
payload: ContractCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if payload.end_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
if not db.query(Asset.id).filter(Asset.id == payload.asset_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
contract = Contract(
|
||||
asset_id=payload.asset_id,
|
||||
contract_type=payload.contract_type,
|
||||
provider_id=payload.provider_id,
|
||||
start_date=payload.start_date,
|
||||
end_date=payload.end_date,
|
||||
coverage_period_text=payload.coverage_period_text.strip() if payload.coverage_period_text else None,
|
||||
renewed_from_id=None,
|
||||
is_superseded=False,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(contract)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": payload.asset_id,
|
||||
"contract_type": payload.contract_type,
|
||||
"provider_id": payload.provider_id,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(payload.end_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_contract(db, contract.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "contract", [contract.id])
|
||||
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{contract_id}", response_model=ContractOut)
|
||||
def update_contract(
|
||||
contract_id: int,
|
||||
payload: ContractUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if contract is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "provider_id" in data and data["provider_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["provider_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
new_start = data.get("start_date", contract.start_date)
|
||||
new_end = data.get("end_date", contract.end_date)
|
||||
if new_end < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(contract, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(contract, k, v)
|
||||
contract.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_contract(db, contract.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "contract", [contract.id])
|
||||
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{contract_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_contract(
|
||||
contract_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if contract is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
||||
|
||||
db.query(Contract).filter(Contract.renewed_from_id == contract.id).update({"renewed_from_id": None})
|
||||
db.query(PMSchedule).filter(PMSchedule.contract_id == contract.id).update({"contract_id": None})
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="delete",
|
||||
changes={"asset_id": contract.asset_id, "contract_type": contract.contract_type},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(contract)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/{contract_id}/renew", response_model=ContractRenewOut)
|
||||
def renew_contract(
|
||||
contract_id: int,
|
||||
payload: ContractRenewIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
old_contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if old_contract is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
||||
|
||||
if payload.end_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
target_provider_id = payload.provider_id if payload.provider_id is not None else old_contract.provider_id
|
||||
if not db.query(Vendor.id).filter(Vendor.id == target_provider_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
old_contract.is_superseded = True
|
||||
old_contract.updated_by_id = current_user.id
|
||||
|
||||
new_contract = Contract(
|
||||
asset_id=old_contract.asset_id,
|
||||
contract_type=payload.contract_type or old_contract.contract_type,
|
||||
provider_id=target_provider_id,
|
||||
start_date=payload.start_date,
|
||||
end_date=payload.end_date,
|
||||
coverage_period_text=(
|
||||
payload.coverage_period_text.strip()
|
||||
if payload.coverage_period_text is not None
|
||||
else old_contract.coverage_period_text
|
||||
),
|
||||
renewed_from_id=old_contract.id,
|
||||
is_superseded=False,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(new_contract)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=old_contract.id,
|
||||
action="renew",
|
||||
changes={
|
||||
"superseded_contract_id": old_contract.id,
|
||||
"new_contract_id": new_contract.id,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(payload.end_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "contract", [old_contract.id, new_contract.id])
|
||||
loaded_old = _load_contract(db, old_contract.id)
|
||||
loaded_new = _load_contract(db, new_contract.id)
|
||||
return ContractRenewOut(
|
||||
old_contract=_to_contract_out(loaded_old, today, lead_days, red_days, att_counts),
|
||||
new_contract=_to_contract_out(loaded_new, today, lead_days, red_days, att_counts),
|
||||
)
|
||||
@@ -0,0 +1,323 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models import DemoEquipment, Department, Location, User, Vendor
|
||||
from ..schemas.demo_equipment import (
|
||||
DemoEquipmentCreate,
|
||||
DemoEquipmentListOut,
|
||||
DemoEquipmentOut,
|
||||
DemoEquipmentReturnIn,
|
||||
DemoEquipmentUpdate,
|
||||
DemoStatusFilter,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/demo-equipment", tags=["demo_equipment"])
|
||||
|
||||
|
||||
def _to_demo_out(
|
||||
item: DemoEquipment,
|
||||
today: date,
|
||||
alert_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> DemoEquipmentOut:
|
||||
if item.actual_return_date is not None:
|
||||
st = "returned"
|
||||
sev = "ok"
|
||||
days_rem = (item.expected_return_date - item.actual_return_date).days
|
||||
elif item.expected_return_date < today:
|
||||
st = "overdue_return"
|
||||
sev = "red"
|
||||
days_rem = (item.expected_return_date - today).days
|
||||
else:
|
||||
st = "on_demo"
|
||||
days_rem = (item.expected_return_date - today).days
|
||||
sev = "yellow" if days_rem <= alert_days else "info"
|
||||
|
||||
return DemoEquipmentOut(
|
||||
id=item.id,
|
||||
name=item.name,
|
||||
equipment_type=item.equipment_type,
|
||||
supplier_id=item.supplier_id,
|
||||
supplier_name=item.supplier.name if item.supplier else None,
|
||||
department_id=item.department_id,
|
||||
department_name=item.department.name if item.department else None,
|
||||
location_id=item.location_id,
|
||||
location_name=item.location.name if item.location else None,
|
||||
start_date=item.start_date,
|
||||
expected_return_date=item.expected_return_date,
|
||||
actual_return_date=item.actual_return_date,
|
||||
status=st,
|
||||
severity=sev,
|
||||
days_remaining=days_rem,
|
||||
attachment_count=att_counts.get(item.id, 0),
|
||||
remarks=item.remarks,
|
||||
created_at=item.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_demo(db: Session, demo_id: int) -> DemoEquipment | None:
|
||||
return (
|
||||
db.query(DemoEquipment)
|
||||
.options(
|
||||
joinedload(DemoEquipment.supplier),
|
||||
joinedload(DemoEquipment.department),
|
||||
joinedload(DemoEquipment.location),
|
||||
)
|
||||
.filter(DemoEquipment.id == demo_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=DemoEquipmentListOut)
|
||||
def list_demo_equipment(
|
||||
q: str = "",
|
||||
supplier_id: Optional[int] = None,
|
||||
department_id: Optional[int] = None,
|
||||
status_filter: Optional[DemoStatusFilter] = Query(None, alias="status"),
|
||||
date_from: Optional[date] = None,
|
||||
date_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
|
||||
query = (
|
||||
db.query(DemoEquipment)
|
||||
.outerjoin(Vendor, DemoEquipment.supplier_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(DemoEquipment.supplier),
|
||||
joinedload(DemoEquipment.department),
|
||||
joinedload(DemoEquipment.location),
|
||||
)
|
||||
)
|
||||
if current_user.role == Role.department_user.value:
|
||||
query = query.filter(DemoEquipment.department_id == current_user.department_id)
|
||||
elif department_id is not None:
|
||||
query = query.filter(DemoEquipment.department_id == department_id)
|
||||
|
||||
if supplier_id is not None:
|
||||
query = query.filter(DemoEquipment.supplier_id == supplier_id)
|
||||
if date_from is not None:
|
||||
query = query.filter(DemoEquipment.expected_return_date >= date_from)
|
||||
if date_to is not None:
|
||||
query = query.filter(DemoEquipment.expected_return_date <= date_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
DemoEquipment.name.ilike(like),
|
||||
DemoEquipment.equipment_type.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
DemoEquipment.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(DemoEquipment.expected_return_date.asc(), DemoEquipment.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [r.id for r in rows])
|
||||
items_all = [_to_demo_out(r, today, alert_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return DemoEquipmentListOut(items=items_all[start : start + page_size], total=total)
|
||||
|
||||
|
||||
@router.post("", response_model=DemoEquipmentOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_demo_equipment(
|
||||
payload: DemoEquipmentCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if payload.expected_return_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="expected_return_date cannot be earlier than start_date.",
|
||||
)
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.supplier_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier vendor not found.")
|
||||
if not db.query(Department.id).filter(Department.id == payload.department_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if payload.location_id is not None:
|
||||
if not db.query(Location.id).filter(Location.id == payload.location_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
|
||||
item = DemoEquipment(
|
||||
name=payload.name.strip(),
|
||||
equipment_type=payload.equipment_type.strip(),
|
||||
supplier_id=payload.supplier_id,
|
||||
department_id=payload.department_id,
|
||||
location_id=payload.location_id,
|
||||
start_date=payload.start_date,
|
||||
expected_return_date=payload.expected_return_date,
|
||||
actual_return_date=None,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(item)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="create",
|
||||
changes={
|
||||
"name": item.name,
|
||||
"supplier_id": payload.supplier_id,
|
||||
"department_id": payload.department_id,
|
||||
"expected_return_date": str(payload.expected_return_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_demo(db, item.id)
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
|
||||
return _to_demo_out(loaded, today, alert_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{demo_id}", response_model=DemoEquipmentOut)
|
||||
def update_demo_equipment(
|
||||
demo_id: int,
|
||||
payload: DemoEquipmentUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
|
||||
if item is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "supplier_id" in data and data["supplier_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["supplier_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier vendor not found.")
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
if not db.query(Department.id).filter(Department.id == data["department_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if "location_id" in data and data["location_id"] is not None:
|
||||
if not db.query(Location.id).filter(Location.id == data["location_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
|
||||
new_start = data.get("start_date", item.start_date)
|
||||
new_exp = data.get("expected_return_date", item.expected_return_date)
|
||||
if new_exp < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="expected_return_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if k in ("name", "equipment_type") and isinstance(v, str):
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"{k} cannot be blank.",
|
||||
)
|
||||
elif k == "remarks" and isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(item, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(item, k, v)
|
||||
item.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_demo(db, item.id)
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
|
||||
return _to_demo_out(loaded, today, alert_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{demo_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_demo_equipment(
|
||||
demo_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
|
||||
if item is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="delete",
|
||||
changes={"name": item.name},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(item)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/{demo_id}/return", response_model=DemoEquipmentOut)
|
||||
def return_demo_equipment(
|
||||
demo_id: int,
|
||||
payload: DemoEquipmentReturnIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
|
||||
if item is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
|
||||
|
||||
if item.actual_return_date is not None:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Demo equipment has already been marked as returned.",
|
||||
code="ALREADY_RETURNED",
|
||||
)
|
||||
|
||||
item.actual_return_date = payload.actual_return_date
|
||||
if payload.remarks and payload.remarks.strip():
|
||||
item.remarks = payload.remarks.strip()
|
||||
item.updated_by_id = current_user.id
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="return",
|
||||
changes={"actual_return_date": str(payload.actual_return_date)},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_demo(db, item.id)
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
|
||||
return _to_demo_out(loaded, today, alert_days, att_counts)
|
||||
@@ -0,0 +1,281 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models import Asset, InsurancePolicy, User, Vendor
|
||||
from ..schemas.insurance import (
|
||||
InsuranceCreate,
|
||||
InsuranceListOut,
|
||||
InsuranceOut,
|
||||
InsuranceStatusFilter,
|
||||
InsuranceUpdate,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/insurance", tags=["insurance"])
|
||||
|
||||
|
||||
def _insurance_lead_settings(db: Session) -> tuple[int, int]:
|
||||
lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"insurance_lead_days",
|
||||
get_setting_value(db, "insurance_expiry_alert_days", 30),
|
||||
)
|
||||
)
|
||||
red = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
return lead, red
|
||||
|
||||
|
||||
def _to_insurance_out(
|
||||
pol: InsurancePolicy,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> InsuranceOut:
|
||||
asset = pol.asset
|
||||
st, sev = coverage_status(pol.start_date, pol.end_date, today, lead_days, red_days)
|
||||
return InsuranceOut(
|
||||
id=pol.id,
|
||||
asset_id=pol.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
insurer_id=pol.insurer_id,
|
||||
insurer_name=pol.insurer.name if pol.insurer else None,
|
||||
policy_no=pol.policy_no,
|
||||
start_date=pol.start_date,
|
||||
end_date=pol.end_date,
|
||||
coverage_amount=pol.coverage_amount,
|
||||
status=st,
|
||||
severity=sev,
|
||||
days_to_expiry=(pol.end_date - today).days,
|
||||
attachment_count=att_counts.get(pol.id, 0),
|
||||
remarks=pol.remarks,
|
||||
created_at=pol.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_insurance(db: Session, policy_id: int) -> InsurancePolicy | None:
|
||||
return (
|
||||
db.query(InsurancePolicy)
|
||||
.options(
|
||||
joinedload(InsurancePolicy.asset).joinedload(Asset.department),
|
||||
joinedload(InsurancePolicy.insurer),
|
||||
)
|
||||
.filter(InsurancePolicy.id == policy_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=InsuranceListOut)
|
||||
def list_insurance_policies(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
insurer_id: Optional[int] = None,
|
||||
status_filter: Optional[InsuranceStatusFilter] = Query(None, alias="status"),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _insurance_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(InsurancePolicy)
|
||||
.join(Asset, InsurancePolicy.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, InsurancePolicy.insurer_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(InsurancePolicy.asset).joinedload(Asset.department),
|
||||
joinedload(InsurancePolicy.insurer),
|
||||
)
|
||||
)
|
||||
if current_user.role == Role.department_user.value:
|
||||
query = query.filter(Asset.department_id == current_user.department_id)
|
||||
elif department_id is not None:
|
||||
query = query.filter(Asset.department_id == department_id)
|
||||
|
||||
if asset_id is not None:
|
||||
query = query.filter(InsurancePolicy.asset_id == asset_id)
|
||||
if insurer_id is not None:
|
||||
query = query.filter(InsurancePolicy.insurer_id == insurer_id)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
InsurancePolicy.policy_no.ilike(like),
|
||||
InsurancePolicy.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(InsurancePolicy.end_date.asc(), InsurancePolicy.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "insurance", [r.id for r in rows])
|
||||
items_all = [_to_insurance_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return InsuranceListOut(items=items_all[start : start + page_size], total=total)
|
||||
|
||||
|
||||
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_insurance_policy(
|
||||
payload: InsuranceCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if payload.end_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
asset = db.query(Asset).filter(Asset.id == payload.asset_id).first()
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.insurer_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurer vendor not found.")
|
||||
|
||||
clean_policy_no = payload.policy_no.strip()
|
||||
if not clean_policy_no:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="policy_no cannot be blank.",
|
||||
)
|
||||
|
||||
asset.insurance_applicable = True
|
||||
pol = InsurancePolicy(
|
||||
asset_id=payload.asset_id,
|
||||
insurer_id=payload.insurer_id,
|
||||
policy_no=clean_policy_no,
|
||||
start_date=payload.start_date,
|
||||
end_date=payload.end_date,
|
||||
coverage_amount=payload.coverage_amount,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(pol)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance",
|
||||
entity_id=pol.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": payload.asset_id,
|
||||
"insurer_id": payload.insurer_id,
|
||||
"policy_no": clean_policy_no,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(payload.end_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_insurance(db, pol.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _insurance_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "insurance", [pol.id])
|
||||
return _to_insurance_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{policy_id}", response_model=InsuranceOut)
|
||||
def update_insurance_policy(
|
||||
policy_id: int,
|
||||
payload: InsuranceUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
pol = db.query(InsurancePolicy).filter(InsurancePolicy.id == policy_id).first()
|
||||
if pol is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurance policy not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "insurer_id" in data and data["insurer_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["insurer_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurer vendor not found.")
|
||||
if "policy_no" in data and data["policy_no"] is not None:
|
||||
clean_no = data["policy_no"].strip()
|
||||
if not clean_no:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="policy_no cannot be blank.",
|
||||
)
|
||||
data["policy_no"] = clean_no
|
||||
|
||||
new_start = data.get("start_date", pol.start_date)
|
||||
new_end = data.get("end_date", pol.end_date)
|
||||
if new_end < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if k == "remarks" and isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(pol, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(pol, k, v)
|
||||
pol.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance",
|
||||
entity_id=pol.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_insurance(db, pol.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _insurance_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "insurance", [pol.id])
|
||||
return _to_insurance_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{policy_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_insurance_policy(
|
||||
policy_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
pol = db.query(InsurancePolicy).filter(InsurancePolicy.id == policy_id).first()
|
||||
if pol is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurance policy not found.")
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance",
|
||||
entity_id=pol.id,
|
||||
action="delete",
|
||||
changes={"asset_id": pol.asset_id, "policy_no": pol.policy_no},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(pol)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,339 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..models import Asset, Complaint, Department, DepartmentVisit, User
|
||||
from ..schemas.visits import (
|
||||
VisitAssetSummary,
|
||||
VisitComplaintSummary,
|
||||
VisitCreate,
|
||||
VisitLinkComplaintIn,
|
||||
VisitListOut,
|
||||
VisitOut,
|
||||
VisitUpdate,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/visits", tags=["visits"])
|
||||
|
||||
|
||||
def _to_visit_out(v: DepartmentVisit) -> VisitOut:
|
||||
return VisitOut(
|
||||
id=v.id,
|
||||
department_id=v.department_id,
|
||||
department_name=v.department.name if v.department else None,
|
||||
visited_by_id=v.visited_by_id,
|
||||
visited_by_name=v.visited_by.name if v.visited_by else None,
|
||||
visit_date=v.visit_date,
|
||||
observations=v.observations,
|
||||
assets=[
|
||||
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
|
||||
for a in v.assets
|
||||
],
|
||||
complaints=[
|
||||
VisitComplaintSummary(
|
||||
id=c.id,
|
||||
complaint_no=c.complaint_no,
|
||||
call_status=c.call_status,
|
||||
priority=c.priority,
|
||||
description=c.description,
|
||||
)
|
||||
for c in v.complaints
|
||||
],
|
||||
created_at=v.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_visit(db: Session, visit_id: int) -> DepartmentVisit | None:
|
||||
return (
|
||||
db.query(DepartmentVisit)
|
||||
.options(
|
||||
joinedload(DepartmentVisit.department),
|
||||
joinedload(DepartmentVisit.visited_by),
|
||||
joinedload(DepartmentVisit.assets),
|
||||
joinedload(DepartmentVisit.complaints),
|
||||
)
|
||||
.filter(DepartmentVisit.id == visit_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _resolve_assets_and_complaints(
|
||||
db: Session,
|
||||
asset_ids: list[int] | None,
|
||||
complaint_ids: list[int] | None,
|
||||
) -> tuple[list[Asset] | None, list[Complaint] | None]:
|
||||
assets_list: list[Asset] | None = None
|
||||
complaints_list: list[Complaint] | None = None
|
||||
|
||||
if asset_ids is not None:
|
||||
unique_aids = list(dict.fromkeys(asset_ids))
|
||||
if unique_aids:
|
||||
found_assets = db.query(Asset).filter(Asset.id.in_(unique_aids)).all()
|
||||
by_id = {a.id: a for a in found_assets}
|
||||
missing = [aid for aid in unique_aids if aid not in by_id]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Assets not found: {missing}",
|
||||
)
|
||||
assets_list = [by_id[aid] for aid in unique_aids]
|
||||
else:
|
||||
assets_list = []
|
||||
|
||||
if complaint_ids is not None:
|
||||
unique_cids = list(dict.fromkeys(complaint_ids))
|
||||
if unique_cids:
|
||||
found_cmps = db.query(Complaint).filter(Complaint.id.in_(unique_cids)).all()
|
||||
by_id = {c.id: c for c in found_cmps}
|
||||
missing = [cid for cid in unique_cids if cid not in by_id]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Complaints not found: {missing}",
|
||||
)
|
||||
complaints_list = [by_id[cid] for cid in unique_cids]
|
||||
else:
|
||||
complaints_list = []
|
||||
|
||||
return assets_list, complaints_list
|
||||
|
||||
|
||||
@router.get("", response_model=VisitListOut)
|
||||
def list_visits(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
visited_by_id: Optional[int] = None,
|
||||
date_from: Optional[date] = None,
|
||||
date_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.management)),
|
||||
):
|
||||
query = (
|
||||
db.query(DepartmentVisit)
|
||||
.join(Department, DepartmentVisit.department_id == Department.id)
|
||||
.join(User, DepartmentVisit.visited_by_id == User.id)
|
||||
.options(
|
||||
joinedload(DepartmentVisit.department),
|
||||
joinedload(DepartmentVisit.visited_by),
|
||||
joinedload(DepartmentVisit.assets),
|
||||
joinedload(DepartmentVisit.complaints),
|
||||
)
|
||||
)
|
||||
if department_id is not None:
|
||||
query = query.filter(DepartmentVisit.department_id == department_id)
|
||||
if visited_by_id is not None:
|
||||
query = query.filter(DepartmentVisit.visited_by_id == visited_by_id)
|
||||
if date_from is not None:
|
||||
query = query.filter(DepartmentVisit.visit_date >= date_from)
|
||||
if date_to is not None:
|
||||
query = query.filter(DepartmentVisit.visit_date <= date_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
DepartmentVisit.observations.ilike(like),
|
||||
Department.name.ilike(like),
|
||||
User.name.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return VisitListOut(items=[_to_visit_out(r) for r in rows], total=total)
|
||||
|
||||
|
||||
@router.get("/{visit_id}", response_model=VisitOut)
|
||||
def get_visit(
|
||||
visit_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.management)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
return _to_visit_out(visit)
|
||||
|
||||
|
||||
@router.post("", response_model=VisitOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_visit(
|
||||
payload: VisitCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
if not db.query(Department.id).filter(Department.id == payload.department_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
|
||||
clean_obs = payload.observations.strip()
|
||||
if not clean_obs:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="observations cannot be blank.",
|
||||
)
|
||||
|
||||
visited_by_id = current_user.id
|
||||
if current_user.role == Role.system_admin.value and payload.visited_by_id is not None:
|
||||
if not db.query(User.id).filter(User.id == payload.visited_by_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visited-by user not found.")
|
||||
visited_by_id = payload.visited_by_id
|
||||
|
||||
assets_list, complaints_list = _resolve_assets_and_complaints(
|
||||
db, payload.asset_ids, payload.complaint_ids
|
||||
)
|
||||
|
||||
visit = DepartmentVisit(
|
||||
department_id=payload.department_id,
|
||||
visited_by_id=visited_by_id,
|
||||
visit_date=payload.visit_date,
|
||||
observations=clean_obs,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
if assets_list is not None:
|
||||
visit.assets = assets_list
|
||||
if complaints_list is not None:
|
||||
visit.complaints = complaints_list
|
||||
|
||||
db.add(visit)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="create",
|
||||
changes={
|
||||
"department_id": payload.department_id,
|
||||
"visit_date": str(payload.visit_date),
|
||||
"asset_ids": [a.id for a in visit.assets],
|
||||
"complaint_ids": [c.id for c in visit.complaints],
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_visit(db, visit.id)
|
||||
return _to_visit_out(loaded)
|
||||
|
||||
|
||||
@router.patch("/{visit_id}", response_model=VisitOut)
|
||||
def update_visit(
|
||||
visit_id: int,
|
||||
payload: VisitUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
if not db.query(Department.id).filter(Department.id == data["department_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
visit.department_id = data["department_id"]
|
||||
if "visit_date" in data and data["visit_date"] is not None:
|
||||
visit.visit_date = data["visit_date"]
|
||||
if "observations" in data and data["observations"] is not None:
|
||||
clean_obs = data["observations"].strip()
|
||||
if not clean_obs:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="observations cannot be blank.",
|
||||
)
|
||||
visit.observations = clean_obs
|
||||
|
||||
assets_list, complaints_list = _resolve_assets_and_complaints(
|
||||
db,
|
||||
data["asset_ids"] if "asset_ids" in data else None,
|
||||
data["complaint_ids"] if "complaint_ids" in data else None,
|
||||
)
|
||||
if assets_list is not None:
|
||||
visit.assets = assets_list
|
||||
if complaints_list is not None:
|
||||
visit.complaints = complaints_list
|
||||
|
||||
visit.updated_by_id = current_user.id
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="update",
|
||||
changes={"updated_fields": list(data.keys())},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_visit(db, visit.id)
|
||||
return _to_visit_out(loaded)
|
||||
|
||||
|
||||
@router.delete("/{visit_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_visit(
|
||||
visit_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
|
||||
visit.assets = []
|
||||
visit.complaints = []
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="delete",
|
||||
changes={"department_id": visit.department_id, "visit_date": str(visit.visit_date)},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(visit)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/{visit_id}/link-complaint", response_model=VisitOut)
|
||||
def link_complaint_to_visit(
|
||||
visit_id: int,
|
||||
payload: VisitLinkComplaintIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
|
||||
complaint = db.query(Complaint).filter(Complaint.id == payload.complaint_id).first()
|
||||
if complaint is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Complaint not found.")
|
||||
|
||||
if all(c.id != complaint.id for c in visit.complaints):
|
||||
visit.complaints.append(complaint)
|
||||
visit.updated_by_id = current_user.id
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="link_complaint",
|
||||
changes={"complaint_id": complaint.id, "complaint_no": complaint.complaint_no},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_visit(db, visit.id)
|
||||
return _to_visit_out(loaded)
|
||||
@@ -0,0 +1,268 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.time_utils import add_months, effective_today
|
||||
from ..models import Asset, User, Vendor, Warranty
|
||||
from ..schemas.warranties import (
|
||||
CoverageStatusFilter,
|
||||
WarrantyCreate,
|
||||
WarrantyListOut,
|
||||
WarrantyOut,
|
||||
WarrantyUpdate,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/warranties", tags=["warranties"])
|
||||
|
||||
|
||||
def _warranty_lead_settings(db: Session) -> tuple[int, int]:
|
||||
lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"warranty_lead_days",
|
||||
get_setting_value(db, "warranty_expiry_alert_days", 30),
|
||||
)
|
||||
)
|
||||
red = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
return lead, red
|
||||
|
||||
|
||||
def _to_warranty_out(
|
||||
w: Warranty,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> WarrantyOut:
|
||||
asset = w.asset
|
||||
st, sev = coverage_status(w.start_date, w.end_date, today, lead_days, red_days)
|
||||
return WarrantyOut(
|
||||
id=w.id,
|
||||
asset_id=w.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
duration_months=w.duration_months,
|
||||
start_date=w.start_date,
|
||||
end_date=w.end_date,
|
||||
provider_id=w.provider_id,
|
||||
provider_name=w.provider.name if w.provider else None,
|
||||
status=st,
|
||||
severity=sev,
|
||||
days_to_expiry=(w.end_date - today).days,
|
||||
attachment_count=att_counts.get(w.id, 0),
|
||||
remarks=w.remarks,
|
||||
created_at=w.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_warranty(db: Session, warranty_id: int) -> Warranty | None:
|
||||
return (
|
||||
db.query(Warranty)
|
||||
.options(
|
||||
joinedload(Warranty.asset).joinedload(Asset.department),
|
||||
joinedload(Warranty.provider),
|
||||
)
|
||||
.filter(Warranty.id == warranty_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=WarrantyListOut)
|
||||
def list_warranties(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
status_filter: Optional[CoverageStatusFilter] = Query(None, alias="status"),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _warranty_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(Warranty)
|
||||
.join(Asset, Warranty.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, Warranty.provider_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(Warranty.asset).joinedload(Asset.department),
|
||||
joinedload(Warranty.provider),
|
||||
)
|
||||
)
|
||||
if current_user.role == Role.department_user.value:
|
||||
query = query.filter(Asset.department_id == current_user.department_id)
|
||||
elif department_id is not None:
|
||||
query = query.filter(Asset.department_id == department_id)
|
||||
|
||||
if asset_id is not None:
|
||||
query = query.filter(Warranty.asset_id == asset_id)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
Warranty.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(Warranty.end_date.asc(), Warranty.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "warranty", [r.id for r in rows])
|
||||
items_all = [_to_warranty_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return WarrantyListOut(items=items_all[start : start + page_size], total=total)
|
||||
|
||||
|
||||
@router.post("", response_model=WarrantyOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_warranty(
|
||||
payload: WarrantyCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if not db.query(Asset.id).filter(Asset.id == payload.asset_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
if payload.provider_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
computed_end = payload.end_date or add_months(payload.start_date, payload.duration_months)
|
||||
if computed_end < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
warranty = Warranty(
|
||||
asset_id=payload.asset_id,
|
||||
duration_months=payload.duration_months,
|
||||
start_date=payload.start_date,
|
||||
end_date=computed_end,
|
||||
provider_id=payload.provider_id,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(warranty)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="warranty",
|
||||
entity_id=warranty.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": payload.asset_id,
|
||||
"duration_months": payload.duration_months,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(computed_end),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_warranty(db, warranty.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _warranty_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "warranty", [warranty.id])
|
||||
return _to_warranty_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{warranty_id}", response_model=WarrantyOut)
|
||||
def update_warranty(
|
||||
warranty_id: int,
|
||||
payload: WarrantyUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
warranty = db.query(Warranty).filter(Warranty.id == warranty_id).first()
|
||||
if warranty is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Warranty not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "provider_id" in data and data["provider_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["provider_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
new_start = data.get("start_date", warranty.start_date)
|
||||
new_duration = data.get("duration_months", warranty.duration_months)
|
||||
if "end_date" in data and data["end_date"] is not None:
|
||||
new_end = data["end_date"]
|
||||
elif "start_date" in data or "duration_months" in data:
|
||||
new_end = add_months(new_start, new_duration)
|
||||
data["end_date"] = new_end
|
||||
else:
|
||||
new_end = warranty.end_date
|
||||
|
||||
if new_end < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(warranty, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(warranty, k, v)
|
||||
warranty.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="warranty",
|
||||
entity_id=warranty.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_warranty(db, warranty.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _warranty_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "warranty", [warranty.id])
|
||||
return _to_warranty_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{warranty_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_warranty(
|
||||
warranty_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
warranty = db.query(Warranty).filter(Warranty.id == warranty_id).first()
|
||||
if warranty is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Warranty not found.")
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="warranty",
|
||||
entity_id=warranty.id,
|
||||
action="delete",
|
||||
changes={"asset_id": warranty.asset_id},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(warranty)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -36,6 +36,23 @@ from .complaints import (
|
||||
ComplaintRestoreIn,
|
||||
ComplaintUpdate,
|
||||
)
|
||||
from .contracts import (
|
||||
ContractCreate,
|
||||
ContractHistoryOut,
|
||||
ContractListOut,
|
||||
ContractOut,
|
||||
ContractRenewIn,
|
||||
ContractRenewOut,
|
||||
ContractUpdate,
|
||||
)
|
||||
from .demo_equipment import (
|
||||
DemoEquipmentCreate,
|
||||
DemoEquipmentListOut,
|
||||
DemoEquipmentOut,
|
||||
DemoEquipmentReturnIn,
|
||||
DemoEquipmentUpdate,
|
||||
)
|
||||
from .insurance import InsuranceCreate, InsuranceListOut, InsuranceOut, InsuranceUpdate
|
||||
from .masters import (
|
||||
CategoryCreate,
|
||||
CategoryOut,
|
||||
@@ -68,6 +85,16 @@ from .pm import (
|
||||
PMScheduleUpdate,
|
||||
)
|
||||
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
|
||||
from .visits import (
|
||||
VisitAssetSummary,
|
||||
VisitComplaintSummary,
|
||||
VisitCreate,
|
||||
VisitLinkComplaintIn,
|
||||
VisitListOut,
|
||||
VisitOut,
|
||||
VisitUpdate,
|
||||
)
|
||||
from .warranties import WarrantyCreate, WarrantyListOut, WarrantyOut, WarrantyUpdate
|
||||
|
||||
__all__ = [
|
||||
"AssetCreate",
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
ContractType = Literal["AMC", "CMC", "OTHER"]
|
||||
ContractStatusFilter = Literal["active", "expiring", "expired", "superseded"]
|
||||
|
||||
|
||||
class ContractCreate(BaseModel):
|
||||
asset_id: int
|
||||
contract_type: ContractType
|
||||
provider_id: int
|
||||
start_date: date
|
||||
end_date: date
|
||||
coverage_period_text: Optional[str] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class ContractUpdate(BaseModel):
|
||||
contract_type: Optional[ContractType] = None
|
||||
provider_id: Optional[int] = None
|
||||
start_date: Optional[date] = None
|
||||
end_date: Optional[date] = None
|
||||
coverage_period_text: Optional[str] = None
|
||||
is_superseded: Optional[bool] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class ContractRenewIn(BaseModel):
|
||||
contract_type: Optional[ContractType] = None
|
||||
provider_id: Optional[int] = None
|
||||
start_date: date
|
||||
end_date: date
|
||||
coverage_period_text: Optional[str] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class ContractOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
contract_type: str
|
||||
provider_id: int
|
||||
provider_name: Optional[str] = None
|
||||
start_date: date
|
||||
end_date: date
|
||||
coverage_period_text: Optional[str] = None
|
||||
renewed_from_id: Optional[int] = None
|
||||
is_superseded: bool
|
||||
status: str
|
||||
severity: str
|
||||
days_to_expiry: int
|
||||
attachment_count: int = 0
|
||||
remarks: Optional[str] = None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ContractListOut(BaseModel):
|
||||
items: list[ContractOut]
|
||||
total: int
|
||||
|
||||
|
||||
class ContractRenewOut(BaseModel):
|
||||
old_contract: ContractOut
|
||||
new_contract: ContractOut
|
||||
|
||||
|
||||
class ContractHistoryOut(BaseModel):
|
||||
items: list[ContractOut]
|
||||
@@ -0,0 +1,61 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
DemoStatusFilter = Literal["on_demo", "overdue_return", "returned"]
|
||||
|
||||
|
||||
class DemoEquipmentCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1)
|
||||
equipment_type: str = Field(..., min_length=1)
|
||||
supplier_id: int
|
||||
department_id: int
|
||||
location_id: Optional[int] = None
|
||||
start_date: date
|
||||
expected_return_date: date
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class DemoEquipmentUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, min_length=1)
|
||||
equipment_type: Optional[str] = Field(None, min_length=1)
|
||||
supplier_id: Optional[int] = None
|
||||
department_id: Optional[int] = None
|
||||
location_id: Optional[int] = None
|
||||
start_date: Optional[date] = None
|
||||
expected_return_date: Optional[date] = None
|
||||
actual_return_date: Optional[date] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class DemoEquipmentReturnIn(BaseModel):
|
||||
actual_return_date: date
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class DemoEquipmentOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
equipment_type: str
|
||||
supplier_id: int
|
||||
supplier_name: Optional[str] = None
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
location_id: Optional[int] = None
|
||||
location_name: Optional[str] = None
|
||||
start_date: date
|
||||
expected_return_date: date
|
||||
actual_return_date: Optional[date] = None
|
||||
status: str
|
||||
severity: str
|
||||
days_remaining: int
|
||||
attachment_count: int = 0
|
||||
remarks: Optional[str] = None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class DemoEquipmentListOut(BaseModel):
|
||||
items: list[DemoEquipmentOut]
|
||||
total: int
|
||||
@@ -0,0 +1,52 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
InsuranceStatusFilter = Literal["active", "expiring", "expired"]
|
||||
|
||||
|
||||
class InsuranceCreate(BaseModel):
|
||||
asset_id: int
|
||||
insurer_id: int
|
||||
policy_no: str = Field(..., min_length=1)
|
||||
start_date: date
|
||||
end_date: date
|
||||
coverage_amount: Optional[float] = Field(None, ge=0)
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class InsuranceUpdate(BaseModel):
|
||||
insurer_id: Optional[int] = None
|
||||
policy_no: Optional[str] = Field(None, min_length=1)
|
||||
start_date: Optional[date] = None
|
||||
end_date: Optional[date] = None
|
||||
coverage_amount: Optional[float] = Field(None, ge=0)
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class InsuranceOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
insurer_id: int
|
||||
insurer_name: Optional[str] = None
|
||||
policy_no: str
|
||||
start_date: date
|
||||
end_date: date
|
||||
coverage_amount: Optional[float] = None
|
||||
status: str
|
||||
severity: str
|
||||
days_to_expiry: int
|
||||
attachment_count: int = 0
|
||||
remarks: Optional[str] = None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class InsuranceListOut(BaseModel):
|
||||
items: list[InsuranceOut]
|
||||
total: int
|
||||
@@ -0,0 +1,58 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class VisitAssetSummary(BaseModel):
|
||||
id: int
|
||||
asset_code: str
|
||||
name: str
|
||||
|
||||
|
||||
class VisitComplaintSummary(BaseModel):
|
||||
id: int
|
||||
complaint_no: str
|
||||
call_status: str
|
||||
priority: str
|
||||
description: str
|
||||
|
||||
|
||||
class VisitCreate(BaseModel):
|
||||
department_id: int
|
||||
visit_date: date
|
||||
observations: str = Field(..., min_length=1)
|
||||
asset_ids: list[int] = Field(default_factory=list)
|
||||
complaint_ids: list[int] = Field(default_factory=list)
|
||||
visited_by_id: Optional[int] = None
|
||||
|
||||
|
||||
class VisitUpdate(BaseModel):
|
||||
department_id: Optional[int] = None
|
||||
visit_date: Optional[date] = None
|
||||
observations: Optional[str] = Field(None, min_length=1)
|
||||
asset_ids: Optional[list[int]] = None
|
||||
complaint_ids: Optional[list[int]] = None
|
||||
|
||||
|
||||
class VisitLinkComplaintIn(BaseModel):
|
||||
complaint_id: int
|
||||
|
||||
|
||||
class VisitOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
visited_by_id: int
|
||||
visited_by_name: Optional[str] = None
|
||||
visit_date: date
|
||||
observations: Optional[str] = None
|
||||
assets: list[VisitAssetSummary] = Field(default_factory=list)
|
||||
complaints: list[VisitComplaintSummary] = Field(default_factory=list)
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class VisitListOut(BaseModel):
|
||||
items: list[VisitOut]
|
||||
total: int
|
||||
@@ -0,0 +1,49 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Literal, Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
CoverageStatusFilter = Literal["active", "expiring", "expired"]
|
||||
|
||||
|
||||
class WarrantyCreate(BaseModel):
|
||||
asset_id: int
|
||||
duration_months: int = Field(..., ge=1, le=240)
|
||||
start_date: date
|
||||
end_date: Optional[date] = None
|
||||
provider_id: Optional[int] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class WarrantyUpdate(BaseModel):
|
||||
duration_months: Optional[int] = Field(None, ge=1, le=240)
|
||||
start_date: Optional[date] = None
|
||||
end_date: Optional[date] = None
|
||||
provider_id: Optional[int] = None
|
||||
remarks: Optional[str] = None
|
||||
|
||||
|
||||
class WarrantyOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
asset_id: int
|
||||
asset_code: str
|
||||
asset_name: str
|
||||
department_id: int
|
||||
department_name: Optional[str] = None
|
||||
duration_months: int
|
||||
start_date: date
|
||||
end_date: date
|
||||
provider_id: Optional[int] = None
|
||||
provider_name: Optional[str] = None
|
||||
status: str
|
||||
severity: str
|
||||
days_to_expiry: int
|
||||
attachment_count: int = 0
|
||||
remarks: Optional[str] = None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class WarrantyListOut(BaseModel):
|
||||
items: list[WarrantyOut]
|
||||
total: int
|
||||
@@ -1,6 +1,7 @@
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
from fastapi import UploadFile
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.config import settings
|
||||
@@ -302,3 +303,15 @@ def delete_attachment(db: Session, user: User, attachment_id: int) -> None:
|
||||
)
|
||||
db.delete(att)
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_attachment_counts(db: Session, entity_type: str, entity_ids: list[int]) -> dict[int, int]:
|
||||
if not entity_ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(Attachment.entity_id, func.count(Attachment.id))
|
||||
.filter(Attachment.entity_type == entity_type, Attachment.entity_id.in_(entity_ids))
|
||||
.group_by(Attachment.entity_id)
|
||||
.all()
|
||||
)
|
||||
return {eid: cnt for eid, cnt in rows}
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
from datetime import date, timedelta
|
||||
import io
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from app.core.time_utils import effective_today
|
||||
from app.models import Asset, Category, Complaint, Contract, Department, Location, Vendor
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_phase5_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("phase5_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
def _make_png_bytes() -> bytes:
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (16, 16), color=(20, 90, 160)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_contract_create_renew_supersede_history_and_scoping(client, db):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||
icu_loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||
cat = db.query(Category).first()
|
||||
provider = db.query(Vendor).filter(Vendor.vendor_type == "service_provider").first()
|
||||
|
||||
# Dedicated asset in ICU for deterministic renewal chain check
|
||||
asset_res = client.post(
|
||||
"/api/assets",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"asset_code": "PHRC-CON-001",
|
||||
"serial_no": "SN-CON-001",
|
||||
"name": "Contract Renewal Test Ventilator",
|
||||
"category_id": cat.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": icu_loc.id,
|
||||
"status": "in_service",
|
||||
"criticality": "critical",
|
||||
},
|
||||
)
|
||||
assert asset_res.status_code == 201
|
||||
asset_id = asset_res.json()["id"]
|
||||
|
||||
# department_user cannot create contracts
|
||||
assert (
|
||||
client.post(
|
||||
"/api/contracts",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"contract_type": "AMC",
|
||||
"provider_id": provider.id,
|
||||
"start_date": "2025-01-01",
|
||||
"end_date": "2025-12-31",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# Coordinator creates initial contract
|
||||
c1_res = client.post(
|
||||
"/api/contracts",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"asset_id": asset_id,
|
||||
"contract_type": "AMC",
|
||||
"provider_id": provider.id,
|
||||
"start_date": "2025-01-01",
|
||||
"end_date": "2025-12-31",
|
||||
"coverage_period_text": "1 Year",
|
||||
"remarks": "Initial AMC",
|
||||
},
|
||||
)
|
||||
assert c1_res.status_code == 201, c1_res.text
|
||||
c1 = c1_res.json()
|
||||
assert c1["is_superseded"] is False
|
||||
|
||||
# Renew contract -> Note N1: old_contract.is_superseded=True, new_contract.renewed_from_id=c1.id
|
||||
renew_res = client.post(
|
||||
f"/api/contracts/{c1['id']}/renew",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"contract_type": "CMC",
|
||||
"start_date": "2026-01-01",
|
||||
"end_date": "2026-12-31",
|
||||
"coverage_period_text": "1 Year Comprehensive",
|
||||
"remarks": "Upgraded to CMC",
|
||||
},
|
||||
)
|
||||
assert renew_res.status_code == 200, renew_res.text
|
||||
rj = renew_res.json()
|
||||
assert rj["old_contract"]["id"] == c1["id"]
|
||||
assert rj["old_contract"]["is_superseded"] is True
|
||||
assert rj["old_contract"]["status"] == "superseded"
|
||||
assert rj["new_contract"]["renewed_from_id"] == c1["id"]
|
||||
assert rj["new_contract"]["is_superseded"] is False
|
||||
assert rj["new_contract"]["contract_type"] == "CMC"
|
||||
|
||||
# History returns both contracts newest first
|
||||
hist_res = client.get(f"/api/contracts/history/{asset_id}", headers=dept_headers)
|
||||
assert hist_res.status_code == 200
|
||||
hist_items = hist_res.json()["items"]
|
||||
assert len(hist_items) == 2
|
||||
assert hist_items[0]["id"] == rj["new_contract"]["id"]
|
||||
assert hist_items[1]["id"] == c1["id"]
|
||||
assert hist_items[1]["is_superseded"] is True
|
||||
|
||||
# include_superseded=false hides superseded contract
|
||||
active_only = client.get(
|
||||
f"/api/contracts?asset_id={asset_id}&include_superseded=false",
|
||||
headers=coord_headers,
|
||||
).json()
|
||||
assert active_only["total"] == 1
|
||||
assert active_only["items"][0]["id"] == rj["new_contract"]["id"]
|
||||
|
||||
# department_user gets 403 on another department's asset history and list only returns ICU
|
||||
ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||
assert client.get(f"/api/contracts/history/{ot_asset.id}", headers=dept_headers).status_code == 403
|
||||
dept_list = client.get("/api/contracts", headers=dept_headers).json()["items"]
|
||||
assert all(item["department_id"] == icu.id for item in dept_list)
|
||||
|
||||
|
||||
def test_warranty_and_insurance_expiry_and_permissions(client, db):
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
|
||||
insurer = db.query(Vendor).filter(Vendor.vendor_type == "insurer").first()
|
||||
today = effective_today(db)
|
||||
|
||||
# department_user cannot write warranty or insurance
|
||||
assert (
|
||||
client.post(
|
||||
"/api/warranties",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"duration_months": 12,
|
||||
"start_date": str(today - timedelta(days=30)),
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/insurance",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"insurer_id": insurer.id,
|
||||
"policy_no": "POL-DENIED",
|
||||
"start_date": str(today),
|
||||
"end_date": str(today + timedelta(days=365)),
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# Coordinator creates expiring warranty (ends in 5 days -> expiring, red)
|
||||
w_start = today - timedelta(days=360)
|
||||
w_end = today + timedelta(days=5)
|
||||
w_res = client.post(
|
||||
"/api/warranties",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"duration_months": 12,
|
||||
"start_date": str(w_start),
|
||||
"end_date": str(w_end),
|
||||
"provider_id": icu_asset.supplier_id,
|
||||
"remarks": "Expiring warranty check",
|
||||
},
|
||||
)
|
||||
assert w_res.status_code == 201, w_res.text
|
||||
wj = w_res.json()
|
||||
assert wj["status"] == "expiring"
|
||||
assert wj["severity"] == "red"
|
||||
assert wj["days_to_expiry"] == 5
|
||||
|
||||
# Coordinator creates expired insurance policy (ended yesterday -> expired, red)
|
||||
ins_res = client.post(
|
||||
"/api/insurance",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"asset_id": icu_asset.id,
|
||||
"insurer_id": insurer.id,
|
||||
"policy_no": "PHRC-POL-TEST-99",
|
||||
"start_date": str(today - timedelta(days=366)),
|
||||
"end_date": str(today - timedelta(days=1)),
|
||||
"coverage_amount": 450000.0,
|
||||
"remarks": "Expired policy check",
|
||||
},
|
||||
)
|
||||
assert ins_res.status_code == 201, ins_res.text
|
||||
ij = ins_res.json()
|
||||
assert ij["status"] == "expired"
|
||||
assert ij["severity"] == "red"
|
||||
assert ij["days_to_expiry"] == -1
|
||||
|
||||
# Upload attachment to insurance -> attachment_count increments to 1
|
||||
up = client.post(
|
||||
"/api/attachments",
|
||||
headers=bio_headers,
|
||||
data={"entity_type": "insurance", "entity_id": str(ij["id"])},
|
||||
files={"file": ("policy.png", _make_png_bytes(), "image/png")},
|
||||
)
|
||||
assert up.status_code == 201
|
||||
fetched = client.get(f"/api/insurance?asset_id={icu_asset.id}", headers=coord_headers).json()["items"]
|
||||
matched = [x for x in fetched if x["id"] == ij["id"]][0]
|
||||
assert matched["attachment_count"] == 1
|
||||
|
||||
|
||||
def test_demo_equipment_overdue_detection_and_return(client, db):
|
||||
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
icu_loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||
supplier = db.query(Vendor).filter(Vendor.vendor_type == "supplier").first()
|
||||
|
||||
# department_user gets 403 on write
|
||||
assert (
|
||||
client.post(
|
||||
"/api/demo-equipment",
|
||||
headers=dept_headers,
|
||||
json={
|
||||
"name": "Unauthorized Demo",
|
||||
"equipment_type": "Monitor",
|
||||
"supplier_id": supplier.id,
|
||||
"department_id": icu.id,
|
||||
"start_date": "2028-01-01",
|
||||
"expected_return_date": "2028-01-10",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/demo-equipment",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"name": "Demo Transport Ventilator X2",
|
||||
"equipment_type": "Ventilator",
|
||||
"supplier_id": supplier.id,
|
||||
"department_id": icu.id,
|
||||
"location_id": icu_loc.id,
|
||||
"start_date": "2028-04-01",
|
||||
"expected_return_date": "2028-04-15",
|
||||
"remarks": "Clinical trial in ICU",
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
demo_id = create_res.json()["id"]
|
||||
|
||||
try:
|
||||
# 1) Set demo_as_of_date = 2028-04-13 (2 days left -> on_demo, yellow)
|
||||
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-13"})
|
||||
r1 = [x for x in client.get("/api/demo-equipment", headers=coord_headers).json()["items"] if x["id"] == demo_id][0]
|
||||
assert r1["status"] == "on_demo"
|
||||
assert r1["severity"] == "yellow"
|
||||
assert r1["days_remaining"] == 2
|
||||
|
||||
# 2) Set demo_as_of_date = 2028-04-20 (past expected_return_date -> overdue_return, red, days_remaining=-5)
|
||||
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": "2028-04-20"})
|
||||
r2 = [x for x in client.get("/api/demo-equipment?status=overdue_return", headers=coord_headers).json()["items"] if x["id"] == demo_id][0]
|
||||
assert r2["status"] == "overdue_return"
|
||||
assert r2["severity"] == "red"
|
||||
assert r2["days_remaining"] == -5
|
||||
|
||||
# 3) Mark returned on 2028-04-18 -> status='returned', severity='ok'
|
||||
ret_res = client.post(
|
||||
f"/api/demo-equipment/{demo_id}/return",
|
||||
headers=coord_headers,
|
||||
json={"actual_return_date": "2028-04-18", "remarks": "Picked up by vendor."},
|
||||
)
|
||||
assert ret_res.status_code == 200, ret_res.text
|
||||
rj = ret_res.json()
|
||||
assert rj["status"] == "returned"
|
||||
assert rj["severity"] == "ok"
|
||||
assert rj["actual_return_date"] == "2028-04-18"
|
||||
finally:
|
||||
client.post("/api/settings/demo-date", headers=admin_headers, json={"demo_as_of_date": None})
|
||||
|
||||
|
||||
def test_department_visits_permissions_and_multi_linking(client, db):
|
||||
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
icu_assets = db.query(Asset).filter(Asset.department_id == icu.id).limit(2).all()
|
||||
complaints = db.query(Complaint).limit(3).all()
|
||||
assert len(icu_assets) >= 2 and len(complaints) >= 3
|
||||
|
||||
# department_user and coordinator get 403 on GET and POST
|
||||
assert client.get("/api/visits", headers=dept_headers).status_code == 403
|
||||
assert client.get("/api/visits", headers=coord_headers).status_code == 403
|
||||
assert (
|
||||
client.post(
|
||||
"/api/visits",
|
||||
headers=coord_headers,
|
||||
json={
|
||||
"department_id": icu.id,
|
||||
"visit_date": "2026-05-10",
|
||||
"observations": "Coordinator denied",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# management can GET (200) but gets 403 on POST
|
||||
assert client.get("/api/visits", headers=mgmt_headers).status_code == 200
|
||||
assert (
|
||||
client.post(
|
||||
"/api/visits",
|
||||
headers=mgmt_headers,
|
||||
json={
|
||||
"department_id": icu.id,
|
||||
"visit_date": "2026-05-10",
|
||||
"observations": "Mgmt write denied",
|
||||
},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# biomedical creates visit with multiple assets and initial complaint
|
||||
create_res = client.post(
|
||||
"/api/visits",
|
||||
headers=bio_headers,
|
||||
json={
|
||||
"department_id": icu.id,
|
||||
"visit_date": "2026-05-10",
|
||||
"observations": "Checked ICU beds 1-4; alarm issue noted on ventilator.",
|
||||
"asset_ids": [a.id for a in icu_assets],
|
||||
"complaint_ids": [complaints[0].id],
|
||||
},
|
||||
)
|
||||
assert create_res.status_code == 201, create_res.text
|
||||
visit = create_res.json()
|
||||
visit_id = visit["id"]
|
||||
assert len(visit["assets"]) == 2
|
||||
assert [c["id"] for c in visit["complaints"]] == [complaints[0].id]
|
||||
|
||||
# management can GET /api/visits/{id} (200) but gets 403 on link-complaint and PATCH
|
||||
assert client.get(f"/api/visits/{visit_id}", headers=mgmt_headers).status_code == 200
|
||||
assert (
|
||||
client.post(
|
||||
f"/api/visits/{visit_id}/link-complaint",
|
||||
headers=mgmt_headers,
|
||||
json={"complaint_id": complaints[1].id},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
client.patch(
|
||||
f"/api/visits/{visit_id}",
|
||||
headers=mgmt_headers,
|
||||
json={"observations": "Should fail"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
|
||||
# biomedical links a second complaint (and linking duplicate is idempotent)
|
||||
link1 = client.post(
|
||||
f"/api/visits/{visit_id}/link-complaint",
|
||||
headers=bio_headers,
|
||||
json={"complaint_id": complaints[1].id},
|
||||
)
|
||||
assert link1.status_code == 200, link1.text
|
||||
assert {c["id"] for c in link1.json()["complaints"]} == {complaints[0].id, complaints[1].id}
|
||||
|
||||
link_dup = client.post(
|
||||
f"/api/visits/{visit_id}/link-complaint",
|
||||
headers=bio_headers,
|
||||
json={"complaint_id": complaints[1].id},
|
||||
)
|
||||
assert link_dup.status_code == 200
|
||||
assert len(link_dup.json()["complaints"]) == 2
|
||||
Reference in New Issue
Block a user