phase-5: contracts, warranties, insurance, demo equipment, and department visits
This commit is contained in:
@@ -58,7 +58,7 @@ cd backend
|
||||
| mgmt@poona.demo | Demo@123 | Management |
|
||||
| coord@poona.demo | Demo@123 | Coordinator |
|
||||
|
||||
## What exists now (Phase 4)
|
||||
## What exists now (Phase 5)
|
||||
- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules
|
||||
- JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login
|
||||
- Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users)
|
||||
@@ -67,6 +67,10 @@ cd backend
|
||||
- Breakdown & Complaint Register (`/complaints` & `/complaints/:id`): sequential complaint numbering, `AssetPicker` raise modal with multi-file attachments, response time & ongoing/milestone downtime calculations, assign/attend/restore/close/reopen workflow with asset status sync, event timeline, admin timestamp correction, and role-enforced technical/CE/spares section (`FORBIDDEN_TECHNICAL_FIELDS` 403 + read-only lock banner)
|
||||
- Preventive Maintenance (`/pm`): in-house & outsourced PM schedules (`/api/pm/schedules`), dynamic read-time `upcoming`/`due`/`overdue`/`completed`/`rescheduled` status & severity evaluation against `effective_today()`, KPI summary strip, Table View & 7-column Mon–Sun Month Calendar View, Complete (auto-advancing next cycle via `add_months`) and Reschedule workflows, plus Asset Detail PM tab actions
|
||||
- Calibration (`/calibration`): single & bulk calibration plan creation (`/api/calibration/plans/from-asset/:assetId`, `/bulk-from-assets`), management/admin/coordinator-gated frequency edit & approval (`FORBIDDEN_CALIBRATION_APPROVAL` 403 for biomedical), dynamic read-time status/severity computation, completion with certificate file upload (`calibration_record` attachments) and auto-generated next due cycle, plus Asset Detail Calibration tab wiring
|
||||
- Contracts & Warranties (`/contracts`): AMC/CMC/OTHER contract CRUD, expiry chips (`amc_cmc_lead_days`, `red_threshold_days`), renewal workflow (`POST /api/contracts/:id/renew` marking prior contract `is_superseded=True` and linking `renewed_from_id`), renewal history chain (`/api/contracts/history/:assetId`), warranty tracking with auto-computed editable end date, and inline document attachments (`contract`/`warranty`)
|
||||
- Asset Insurance (`/insurance`) & Slide-Over `InsuranceDrawer`: insurance policy register with INR coverage display, expiry alerts, policy attachments (`insurance`), and `"View Insurance"` drawer accessible from `AssetDetailPage`, `AssetPicker`, and `ComplaintDetailPage`
|
||||
- Demo Equipment (`/demo-equipment`): trial equipment register with dynamic `on_demo`/`overdue_return`/`returned` status relative to `effective_today()`, return logging (`POST /api/demo-equipment/:id/return`), and `demo_equipment` attachments
|
||||
- Department Visits (`/visits`): biomedical/admin round logs with management read access (403 for `department_user` and `coordinator`), department-filtered multi-asset checklist, observations, and complaint creation/linking (`POST /api/visits/:id/link-complaint`)
|
||||
- Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges
|
||||
- Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete)
|
||||
- Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data
|
||||
|
||||
+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
|
||||
@@ -13,12 +13,12 @@ import { ComplaintsPage } from "@/pages/ComplaintsPage";
|
||||
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
|
||||
import { PMPage } from "@/pages/PMPage";
|
||||
import { CalibrationPage } from "@/pages/CalibrationPage";
|
||||
import { ContractsPage } from "@/pages/ContractsPage";
|
||||
import { InsurancePage } from "@/pages/InsurancePage";
|
||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||
import { VisitsPage } from "@/pages/VisitsPage";
|
||||
import {
|
||||
DashboardPage,
|
||||
ContractsPage,
|
||||
InsurancePage,
|
||||
DemoEquipmentPage,
|
||||
VisitsPage,
|
||||
ReportsPage,
|
||||
NotificationsPage,
|
||||
} from "@/pages/stubs";
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
import { api } from "./client";
|
||||
import type { AlertSeverity, CoverageStatus } from "./assets";
|
||||
|
||||
export type ContractStatus = CoverageStatus | "superseded";
|
||||
export type DemoStatus = "on_demo" | "overdue_return" | "returned";
|
||||
|
||||
export interface ContractItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
contract_type: string;
|
||||
provider_id: number;
|
||||
provider_name: string | null;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_period_text: string | null;
|
||||
renewed_from_id: number | null;
|
||||
is_superseded: boolean;
|
||||
status: ContractStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ContractListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
provider_id?: number;
|
||||
contract_type?: string;
|
||||
status?: string;
|
||||
include_superseded?: boolean;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface ContractCreatePayload {
|
||||
asset_id: number;
|
||||
contract_type: string;
|
||||
provider_id: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_period_text?: string | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface ContractRenewPayload {
|
||||
contract_type?: string;
|
||||
provider_id?: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_period_text?: string | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface WarrantyItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
duration_months: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
provider_id: number | null;
|
||||
provider_name: string | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface WarrantyListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
status?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface WarrantyCreatePayload {
|
||||
asset_id: number;
|
||||
duration_months: number;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
provider_id?: number | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface InsuranceItem {
|
||||
id: number;
|
||||
asset_id: number;
|
||||
asset_code: string;
|
||||
asset_name: string;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
insurer_id: number;
|
||||
insurer_name: string | null;
|
||||
policy_no: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_amount: number | null;
|
||||
status: CoverageStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_to_expiry: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface InsuranceListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
asset_id?: number;
|
||||
insurer_id?: number;
|
||||
status?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface InsuranceCreatePayload {
|
||||
asset_id: number;
|
||||
insurer_id: number;
|
||||
policy_no: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
coverage_amount?: number | null;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface DemoEquipmentItem {
|
||||
id: number;
|
||||
name: string;
|
||||
equipment_type: string;
|
||||
supplier_id: number;
|
||||
supplier_name: string | null;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
location_id: number | null;
|
||||
location_name: string | null;
|
||||
start_date: string;
|
||||
expected_return_date: string;
|
||||
actual_return_date: string | null;
|
||||
status: DemoStatus | string;
|
||||
severity: AlertSeverity | string;
|
||||
days_remaining: number;
|
||||
attachment_count: number;
|
||||
remarks: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface DemoListParams {
|
||||
q?: string;
|
||||
supplier_id?: number;
|
||||
department_id?: number;
|
||||
status?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface DemoCreatePayload {
|
||||
name: string;
|
||||
equipment_type: string;
|
||||
supplier_id: number;
|
||||
department_id: number;
|
||||
location_id?: number | null;
|
||||
start_date: string;
|
||||
expected_return_date: string;
|
||||
remarks?: string | null;
|
||||
}
|
||||
|
||||
export interface VisitAssetBrief {
|
||||
id: number;
|
||||
asset_code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface VisitComplaintBrief {
|
||||
id: number;
|
||||
complaint_no: string;
|
||||
call_status: string;
|
||||
priority: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface VisitItem {
|
||||
id: number;
|
||||
department_id: number;
|
||||
department_name: string | null;
|
||||
visited_by_id: number;
|
||||
visited_by_name: string | null;
|
||||
visit_date: string;
|
||||
observations: string;
|
||||
assets: VisitAssetBrief[];
|
||||
complaints: VisitComplaintBrief[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface VisitListParams {
|
||||
q?: string;
|
||||
department_id?: number;
|
||||
visited_by_id?: number;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface VisitCreatePayload {
|
||||
department_id: number;
|
||||
visit_date: string;
|
||||
observations: string;
|
||||
asset_ids?: number[];
|
||||
complaint_ids?: number[];
|
||||
}
|
||||
|
||||
function toQS(params: Record<string, string | number | boolean | undefined>): string {
|
||||
const sp = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v === undefined || v === "") continue;
|
||||
sp.set(k, String(v));
|
||||
}
|
||||
const s = sp.toString();
|
||||
return s ? `?${s}` : "";
|
||||
}
|
||||
|
||||
export const contractsApi = {
|
||||
list: (params: ContractListParams = {}) =>
|
||||
api.get<{ items: ContractItem[]; total: number }>(
|
||||
`/contracts${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: ContractCreatePayload) => api.post<ContractItem>("/contracts", data),
|
||||
update: (id: number, data: Partial<ContractCreatePayload>) =>
|
||||
api.patch<ContractItem>(`/contracts/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/contracts/${id}`),
|
||||
renew: (id: number, data: ContractRenewPayload) =>
|
||||
api.post<{ old_contract: ContractItem; new_contract: ContractItem }>(
|
||||
`/contracts/${id}/renew`,
|
||||
data
|
||||
),
|
||||
history: (assetId: number) =>
|
||||
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
|
||||
};
|
||||
|
||||
export const warrantiesApi = {
|
||||
list: (params: WarrantyListParams = {}) =>
|
||||
api.get<{ items: WarrantyItem[]; total: number }>(
|
||||
`/warranties${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: WarrantyCreatePayload) => api.post<WarrantyItem>("/warranties", data),
|
||||
update: (id: number, data: Partial<WarrantyCreatePayload>) =>
|
||||
api.patch<WarrantyItem>(`/warranties/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/warranties/${id}`),
|
||||
};
|
||||
|
||||
export const insuranceApi = {
|
||||
list: (params: InsuranceListParams = {}) =>
|
||||
api.get<{ items: InsuranceItem[]; total: number }>(
|
||||
`/insurance${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: InsuranceCreatePayload) => api.post<InsuranceItem>("/insurance", data),
|
||||
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
|
||||
api.patch<InsuranceItem>(`/insurance/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
|
||||
};
|
||||
|
||||
export const demoEquipmentApi = {
|
||||
list: (params: DemoListParams = {}) =>
|
||||
api.get<{ items: DemoEquipmentItem[]; total: number }>(
|
||||
`/demo-equipment${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
create: (data: DemoCreatePayload) =>
|
||||
api.post<DemoEquipmentItem>("/demo-equipment", data),
|
||||
update: (id: number, data: Partial<DemoCreatePayload>) =>
|
||||
api.patch<DemoEquipmentItem>(`/demo-equipment/${id}`, data),
|
||||
remove: (id: number) => api.delete<void>(`/demo-equipment/${id}`),
|
||||
markReturned: (id: number, data: { actual_return_date: string; remarks?: string | null }) =>
|
||||
api.post<DemoEquipmentItem>(`/demo-equipment/${id}/return`, data),
|
||||
};
|
||||
|
||||
export const visitsApi = {
|
||||
list: (params: VisitListParams = {}) =>
|
||||
api.get<{ items: VisitItem[]; total: number }>(
|
||||
`/visits${toQS(params as Record<string, string | number | boolean | undefined>)}`
|
||||
),
|
||||
get: (id: number) => api.get<VisitItem>(`/visits/${id}`),
|
||||
create: (data: VisitCreatePayload) => api.post<VisitItem>("/visits", data),
|
||||
update: (id: number, data: Partial<VisitCreatePayload>) =>
|
||||
api.patch<VisitItem>(`/visits/${id}`, data),
|
||||
linkComplaint: (id: number, complaintId: number) =>
|
||||
api.post<VisitItem>(`/visits/${id}/link-complaint`, { complaint_id: complaintId }),
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import { Search, X, ShieldCheck, Ban } from "lucide-react";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { CoverageBadge, AssetStatusBadge } from "./StatusBadge";
|
||||
import { InsuranceDrawer } from "./InsuranceDrawer";
|
||||
|
||||
interface AssetPickerProps {
|
||||
selectedAsset: AssetLookupItem | null;
|
||||
@@ -24,6 +25,7 @@ export function AssetPicker({
|
||||
const [results, setResults] = useState<AssetLookupItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [insuranceOpen, setInsuranceOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -148,11 +150,28 @@ export function AssetPicker({
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Insurance</div>
|
||||
<div className="font-medium text-gray-800">
|
||||
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-medium text-gray-800">
|
||||
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInsuranceOpen(true)}
|
||||
className="text-xs font-medium text-[#1e3a8a] hover:underline"
|
||||
>
|
||||
View Insurance
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{insuranceOpen && (
|
||||
<InsuranceDrawer
|
||||
open={insuranceOpen}
|
||||
onClose={() => setInsuranceOpen(false)}
|
||||
assetId={selectedAsset.id}
|
||||
assetLabel={`${selectedAsset.asset_code} — ${selectedAsset.name}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useEffect } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Link } from "react-router-dom";
|
||||
import { X, ShieldCheck, AlertCircle, ExternalLink } from "lucide-react";
|
||||
import { insuranceApi } from "@/api/phase5";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate, formatINR } from "@/lib/format";
|
||||
import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface InsuranceDrawerProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
assetId: number | null;
|
||||
assetLabel?: string;
|
||||
}
|
||||
|
||||
export function InsuranceDrawer({
|
||||
open,
|
||||
onClose,
|
||||
assetId,
|
||||
assetLabel,
|
||||
}: InsuranceDrawerProps) {
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const canManage = can(role, "manage_calibration_contracts");
|
||||
|
||||
const policiesQuery = useQuery({
|
||||
queryKey: ["insurance", "asset-drawer", assetId],
|
||||
queryFn: () => insuranceApi.list({ asset_id: assetId!, page_size: 200 }),
|
||||
enabled: open && Boolean(assetId),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open || !assetId) return null;
|
||||
|
||||
const policies = policiesQuery.data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex justify-end bg-black/40"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Asset Insurance Policies"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-lg bg-white h-full shadow-2xl border-l border-gray-200 flex flex-col"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 bg-gray-50">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-gray-900">
|
||||
<ShieldCheck className="h-4 w-4 text-[#1e3a8a] shrink-0" />
|
||||
<span>Asset Insurance</span>
|
||||
</div>
|
||||
{assetLabel && (
|
||||
<p className="text-xs text-gray-500 truncate mt-0.5">{assetLabel}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close insurance drawer"
|
||||
className="p-1.5 rounded-md text-gray-500 hover:text-gray-800 hover:bg-gray-200"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-5 space-y-4">
|
||||
{policiesQuery.isLoading ? (
|
||||
<div className="space-y-3">
|
||||
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
|
||||
<div className="h-28 bg-gray-100 rounded-lg animate-pulse" />
|
||||
</div>
|
||||
) : policiesQuery.isError ? (
|
||||
<div className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>Failed to load insurance policies for this asset.</span>
|
||||
</div>
|
||||
) : policies.length === 0 ? (
|
||||
<div className="text-center py-10 bg-gray-50 border border-dashed border-gray-200 rounded-lg space-y-2">
|
||||
<ShieldCheck className="h-8 w-8 text-gray-300 mx-auto" />
|
||||
<p className="text-sm font-medium text-gray-700">
|
||||
No insurance policies recorded for this asset.
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Policies can be added from the Insurance register.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
policies.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="rounded-lg border border-gray-200 bg-white p-4 space-y-3 shadow-sm"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="font-mono text-sm font-bold text-[#1e3a8a]">
|
||||
{p.policy_no}
|
||||
</div>
|
||||
<div className="text-xs text-gray-600 mt-0.5">
|
||||
{p.insurer_name || `Insurer #${p.insurer_id}`}
|
||||
</div>
|
||||
</div>
|
||||
<ExpiryChip
|
||||
daysToExpiry={p.days_to_expiry}
|
||||
status={p.status}
|
||||
severity={p.severity}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 text-xs bg-gray-50 rounded-md p-2.5 border border-gray-100">
|
||||
<div>
|
||||
<div className="text-gray-500">Start</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatDate(p.start_date)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">End</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatDate(p.end_date)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-gray-500">Coverage</div>
|
||||
<div className="font-medium text-gray-900">
|
||||
{formatINR(p.coverage_amount)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{p.remarks && (
|
||||
<p className="text-xs text-gray-600">
|
||||
<span className="font-medium">Remarks:</span> {p.remarks}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="pt-2 border-t border-gray-100">
|
||||
<div className="text-xs font-semibold text-gray-700 mb-1.5">
|
||||
Policy Certificates & Documents
|
||||
</div>
|
||||
<Attachments
|
||||
entityType="insurance"
|
||||
entityId={p.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-5 py-3 border-t border-gray-200 bg-gray-50 flex items-center justify-between gap-2">
|
||||
<Link to={`/insurance`} onClick={onClose}>
|
||||
<Button variant="outline" size="sm">
|
||||
<ExternalLink className="h-3.5 w-3.5 mr-1.5" />
|
||||
Open Insurance Register
|
||||
</Button>
|
||||
</Link>
|
||||
<Button variant="outline" size="sm" onClick={onClose}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import { Button } from "@/components/ui/button";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { validateAttachmentFile } from "@/components/Attachments";
|
||||
import { ApiError } from "@/api/client";
|
||||
import type { AssetLookupItem, AssetCriticality } from "@/api/assets";
|
||||
import { complaintsApi } from "@/api/complaints";
|
||||
import { assetsApi, type AssetLookupItem, type AssetCriticality } from "@/api/assets";
|
||||
import { complaintsApi, type ComplaintItem } from "@/api/complaints";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { fetchUsersLookup } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
@@ -29,13 +29,24 @@ type ComplaintFormValues = z.infer<typeof complaintSchema>;
|
||||
interface RaiseComplaintModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
initialAssetId?: number | null;
|
||||
initialDescription?: string;
|
||||
onCreated?: (complaint: ComplaintItem) => Promise<void> | void;
|
||||
navigateOnCreate?: boolean;
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
|
||||
export function RaiseComplaintModal({ open, onClose }: RaiseComplaintModalProps) {
|
||||
export function RaiseComplaintModal({
|
||||
open,
|
||||
onClose,
|
||||
initialAssetId = null,
|
||||
initialDescription = "",
|
||||
onCreated,
|
||||
navigateOnCreate = true,
|
||||
}: RaiseComplaintModalProps) {
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
@@ -69,17 +80,39 @@ export function RaiseComplaintModal({ open, onClose }: RaiseComplaintModalProps)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setSelectedAsset(null);
|
||||
setFiles([]);
|
||||
setServerError(null);
|
||||
reset({
|
||||
description: "",
|
||||
description: initialDescription,
|
||||
breakdown_details: "",
|
||||
priority: "non_critical",
|
||||
notes: "",
|
||||
received_by_id: user?.id ? String(user.id) : "",
|
||||
});
|
||||
}, [open, user?.id, reset]);
|
||||
if (initialAssetId) {
|
||||
let cancelled = false;
|
||||
assetsApi
|
||||
.get(initialAssetId)
|
||||
.then((a) => {
|
||||
if (cancelled) return;
|
||||
setSelectedAsset({
|
||||
...a,
|
||||
contract_summary: a.contract_type
|
||||
? `${a.contract_type} (${a.contract_status})`
|
||||
: "None",
|
||||
insurance_summary: a.insurance_status || "None",
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setSelectedAsset(null);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
} else {
|
||||
setSelectedAsset(null);
|
||||
}
|
||||
}, [open, user?.id, initialAssetId, initialDescription, reset]);
|
||||
|
||||
function handleFilePick(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const picked = Array.from(e.target.files ?? []);
|
||||
@@ -117,8 +150,13 @@ export function RaiseComplaintModal({ open, onClose }: RaiseComplaintModalProps)
|
||||
|
||||
await qc.invalidateQueries({ queryKey: ["complaints"] });
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
if (onCreated) {
|
||||
await onCreated(created);
|
||||
}
|
||||
onClose();
|
||||
navigate(`/complaints/${created.id}`);
|
||||
if (navigateOnCreate) {
|
||||
navigate(`/complaints/${created.id}`);
|
||||
}
|
||||
} catch (err) {
|
||||
setServerError(err instanceof ApiError ? err.detail : "Failed to register complaint.");
|
||||
}
|
||||
|
||||
@@ -306,3 +306,120 @@ export function CallStatusBadge({
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ExpiryChip({
|
||||
daysToExpiry,
|
||||
status,
|
||||
severity,
|
||||
className,
|
||||
}: {
|
||||
daysToExpiry: number;
|
||||
status: string;
|
||||
severity?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
if (status === "superseded") {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-gray-100 text-gray-600 border border-gray-300",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<MinusCircle className="h-3 w-3 shrink-0" />
|
||||
Superseded
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "expired" || daysToExpiry < 0) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-red-100 text-red-800 border border-red-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<AlertCircle className="h-3 w-3 shrink-0" />
|
||||
Expired
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "expiring") {
|
||||
const isRed = severity === "red";
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap border",
|
||||
isRed
|
||||
? "bg-red-100 text-red-800 border-red-200"
|
||||
: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="h-3 w-3 shrink-0" />
|
||||
{daysToExpiry} {daysToExpiry === 1 ? "day" : "days"} left
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-green-100 text-green-800 border border-green-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3 shrink-0" />
|
||||
Active
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function DemoStatusBadge({
|
||||
status,
|
||||
daysRemaining,
|
||||
className,
|
||||
}: {
|
||||
status: string;
|
||||
daysRemaining?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
if (status === "returned") {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-green-100 text-green-800 border border-green-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3 shrink-0" />
|
||||
Returned
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "overdue_return") {
|
||||
const overdueDays =
|
||||
daysRemaining != null && daysRemaining < 0 ? Math.abs(daysRemaining) : null;
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-red-100 text-red-800 border border-red-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<AlertTriangle className="h-3 w-3 shrink-0" />
|
||||
{overdueDays != null ? `Overdue by ${overdueDays}d` : "Overdue Return"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap bg-blue-100 text-blue-800 border border-blue-200",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Clock className="h-3 w-3 shrink-0" />
|
||||
On Demo
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import {
|
||||
NewPMScheduleModal,
|
||||
CompletePMModal,
|
||||
@@ -64,6 +65,7 @@ export function AssetDetailPage() {
|
||||
|
||||
const [activeTab, setActiveTab] = useState<DetailTab>("overview");
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [insuranceDrawerOpen, setInsuranceDrawerOpen] = useState(false);
|
||||
const [addCalOpen, setAddCalOpen] = useState(false);
|
||||
const [approveCalOpen, setApproveCalOpen] = useState(false);
|
||||
const [newPMOpen, setNewPMOpen] = useState(false);
|
||||
@@ -169,12 +171,18 @@ export function AssetDetailPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{canEdit && (
|
||||
<Button variant="outline" onClick={() => setEditOpen(true)}>
|
||||
<Pencil className="h-4 w-4 mr-1.5" />
|
||||
Edit Asset
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={() => setInsuranceDrawerOpen(true)}>
|
||||
<ShieldCheck className="h-4 w-4 mr-1.5" />
|
||||
View Insurance
|
||||
</Button>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button variant="outline" onClick={() => setEditOpen(true)}>
|
||||
<Pencil className="h-4 w-4 mr-1.5" />
|
||||
Edit Asset
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 pt-3 border-t border-gray-100 text-sm">
|
||||
@@ -625,6 +633,12 @@ export function AssetDetailPage() {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<InsuranceDrawer
|
||||
open={insuranceDrawerOpen}
|
||||
onClose={() => setInsuranceDrawerOpen(false)}
|
||||
assetId={asset.id}
|
||||
assetLabel={`${asset.asset_code} — ${asset.name}`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
CalendarCog,
|
||||
Info,
|
||||
Activity,
|
||||
ShieldCheck,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
complaintsApi,
|
||||
@@ -34,6 +35,7 @@ import {
|
||||
CriticalityBadge,
|
||||
} from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
|
||||
function toDatetimeLocal(iso: string | null | undefined): string {
|
||||
if (!iso) return "";
|
||||
@@ -96,6 +98,7 @@ export function ComplaintDetailPage() {
|
||||
const [tsField, setTsField] = useState<TimestampField>("attended_at");
|
||||
const [tsValue, setTsValue] = useState("");
|
||||
const [tsReason, setTsReason] = useState("");
|
||||
const [insuranceDrawerOpen, setInsuranceDrawerOpen] = useState(false);
|
||||
|
||||
// Technical form state
|
||||
const [actionTaken, setActionTaken] = useState("");
|
||||
@@ -791,11 +794,22 @@ export function ComplaintDetailPage() {
|
||||
<div>Department: {c.department_name || "—"}</div>
|
||||
<div>Location: {c.location_name || "—"}</div>
|
||||
</div>
|
||||
<Link to={`/assets/${c.asset_id}`} className="block pt-1">
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
View Asset Record
|
||||
<div className="space-y-2 pt-1">
|
||||
<Link to={`/assets/${c.asset_id}`} className="block">
|
||||
<Button variant="outline" size="sm" className="w-full">
|
||||
View Asset Record
|
||||
</Button>
|
||||
</Link>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => setInsuranceDrawerOpen(true)}
|
||||
>
|
||||
<ShieldCheck className="h-3.5 w-3.5 mr-1.5" />
|
||||
View Insurance
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border border-gray-200 p-4 shadow-sm space-y-3">
|
||||
@@ -985,6 +999,13 @@ export function ComplaintDetailPage() {
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
<InsuranceDrawer
|
||||
open={insuranceDrawerOpen}
|
||||
onClose={() => setInsuranceDrawerOpen(false)}
|
||||
assetId={c.asset_id}
|
||||
assetLabel={`${c.asset_code} — ${c.asset_name}`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,703 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Trash2,
|
||||
CornerDownLeft,
|
||||
Search,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { demoEquipmentApi, type DemoEquipmentItem } from "@/api/phase5";
|
||||
import { departmentsApi, locationsApi, vendorsApi } from "@/api/masters";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { DemoStatusBadge } from "@/components/StatusBadge";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
|
||||
type ViewTab = "active" | "returned" | "all";
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
|
||||
export function DemoEquipmentPage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const isDeptUser = role === "department_user";
|
||||
const canManage = can(role, "manage_demo_equipment");
|
||||
|
||||
const [viewTab, setViewTab] = useState<ViewTab>("active");
|
||||
const [q, setQ] = useState("");
|
||||
const [supplierId, setSupplierId] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<DemoEquipmentItem | null>(null);
|
||||
const [returnTarget, setReturnTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
const [attachTarget, setAttachTarget] = useState<DemoEquipmentItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const locationsQuery = useQuery({
|
||||
queryKey: ["locations", "active-only"],
|
||||
queryFn: () => locationsApi.list(false),
|
||||
});
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
});
|
||||
|
||||
const demoQuery = useQuery({
|
||||
queryKey: [
|
||||
"demo-equipment",
|
||||
viewTab,
|
||||
q,
|
||||
supplierId,
|
||||
departmentId,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
],
|
||||
queryFn: () =>
|
||||
demoEquipmentApi.list({
|
||||
q: q.trim() || undefined,
|
||||
supplier_id: supplierId ? Number(supplierId) : undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
status: viewTab === "returned" ? "returned" : undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => demoEquipmentApi.remove(id),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ["demo-equipment"] }),
|
||||
});
|
||||
|
||||
const items = useMemo(() => {
|
||||
const raw = demoQuery.data?.items ?? [];
|
||||
if (viewTab === "active") {
|
||||
return raw.filter((item) => item.status !== "returned");
|
||||
}
|
||||
if (viewTab === "returned") {
|
||||
return raw.filter((item) => item.status === "returned");
|
||||
}
|
||||
return raw;
|
||||
}, [demoQuery.data?.items, viewTab]);
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const locations = locationsQuery.data?.items ?? [];
|
||||
const allVendors = vendorsQuery.data?.items ?? [];
|
||||
const suppliers = allVendors.filter((v) => v.vendor_type === "supplier");
|
||||
const supplierOptions = suppliers.length ? suppliers : allVendors;
|
||||
|
||||
const columns: ColumnDef<DemoEquipmentItem, unknown>[] = [
|
||||
{
|
||||
id: "equipment",
|
||||
accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""}`,
|
||||
header: "Equipment",
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<div className="font-medium text-gray-900">{row.original.name}</div>
|
||||
{row.original.equipment_type && (
|
||||
<div className="text-xs text-gray-500">{row.original.equipment_type}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "supplier_name",
|
||||
header: "Supplier",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
id: "dept_loc",
|
||||
accessorFn: (r) => `${r.department_name ?? ""} ${r.location_name ?? ""}`,
|
||||
header: "Department / Location",
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<div className="text-gray-800">{row.original.department_name || "—"}</div>
|
||||
{row.original.location_name && (
|
||||
<div className="text-xs text-gray-500">{row.original.location_name}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: "Start Date",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "expected_return_date",
|
||||
header: "Expected Return",
|
||||
cell: ({ row }) => (
|
||||
<span
|
||||
className={`whitespace-nowrap ${
|
||||
row.original.status === "overdue_return" ? "font-semibold text-red-700" : ""
|
||||
}`}
|
||||
>
|
||||
{formatDate(row.original.expected_return_date)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "actual_return_date",
|
||||
header: "Actual Return",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string | null)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: "Status",
|
||||
cell: ({ row }) => (
|
||||
<DemoStatusBadge
|
||||
status={row.original.status}
|
||||
daysRemaining={row.original.days_remaining}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: "Docs",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setAttachTarget(row.original)}
|
||||
title="View or upload demo equipment documents"
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
<span className="text-xs">{row.original.attachment_count}</span>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
...(canManage
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: DemoEquipmentItem } }) => (
|
||||
<div className="flex items-center gap-1">
|
||||
{row.original.status !== "returned" && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setReturnTarget(row.original)}
|
||||
>
|
||||
<CornerDownLeft className="h-3.5 w-3.5 mr-1" />
|
||||
Return
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditing(row.original);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
aria-label={`Edit demo equipment ${row.original.name}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete demo entry "${row.original.name}"?`)) {
|
||||
deleteMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
aria-label={`Delete demo equipment ${row.original.name}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
} satisfies ColumnDef<DemoEquipmentItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Demo Equipment Register</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Monitor supplier trial equipment, expected return dates, and overdue alerts
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Log Demo Equipment
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* View Tabs */}
|
||||
<div className="flex gap-1 border-b border-gray-200">
|
||||
{(
|
||||
[
|
||||
{ key: "active", label: "Active & Overdue" },
|
||||
{ key: "returned", label: "Returned History" },
|
||||
{ key: "all", label: "All" },
|
||||
] as { key: ViewTab; label: string }[]
|
||||
).map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
onClick={() => setViewTab(t.key)}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
|
||||
viewTab === t.key
|
||||
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5">
|
||||
<div className="relative lg:col-span-2">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search equipment name, type, remarks..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={supplierId}
|
||||
onChange={(e) => setSupplierId(e.target.value)}
|
||||
aria-label="Filter by Supplier"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Suppliers</option>
|
||||
{supplierOptions.map((s) => (
|
||||
<option key={s.id} value={String(s.id)}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{!isDeptUser && (
|
||||
<select
|
||||
value={departmentId}
|
||||
onChange={(e) => setDepartmentId(e.target.value)}
|
||||
aria-label="Filter by Department"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Departments</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Start Date From"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Start Date To"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={items}
|
||||
columns={columns}
|
||||
loading={demoQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter demo equipment..."
|
||||
exportFilename="demo-equipment"
|
||||
emptyMessage="No demo equipment entries found."
|
||||
/>
|
||||
|
||||
<DemoFormModal
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
editing={editing}
|
||||
suppliers={supplierOptions}
|
||||
departments={departments}
|
||||
locations={locations}
|
||||
/>
|
||||
|
||||
<ReturnDemoModal
|
||||
open={Boolean(returnTarget)}
|
||||
onClose={() => setReturnTarget(null)}
|
||||
item={returnTarget}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(attachTarget)}
|
||||
onOpenChange={(o) => !o && setAttachTarget(null)}
|
||||
title={`Documents — ${attachTarget?.name ?? ""}`}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{attachTarget && (
|
||||
<Attachments
|
||||
entityType="demo_equipment"
|
||||
entityId={attachTarget.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DemoFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
suppliers,
|
||||
departments,
|
||||
locations,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: DemoEquipmentItem | null;
|
||||
suppliers: Array<{ id: number; name: string }>;
|
||||
departments: Array<{ id: number; name: string }>;
|
||||
locations: Array<{ id: number; department_id: number; name: string }>;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [name, setName] = useState("");
|
||||
const [equipmentType, setEquipmentType] = useState("");
|
||||
const [supplierId, setSupplierId] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [locationId, setLocationId] = useState("");
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [expectedReturnDate, setExpectedReturnDate] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
if (editing) {
|
||||
setName(editing.name);
|
||||
setEquipmentType(editing.equipment_type ?? "");
|
||||
setSupplierId(String(editing.supplier_id));
|
||||
setDepartmentId(String(editing.department_id));
|
||||
setLocationId(editing.location_id ? String(editing.location_id) : "");
|
||||
setStartDate(editing.start_date);
|
||||
setExpectedReturnDate(editing.expected_return_date);
|
||||
setRemarks(editing.remarks ?? "");
|
||||
} else {
|
||||
const today = new Date();
|
||||
const plus14 = new Date(today);
|
||||
plus14.setDate(plus14.getDate() + 14);
|
||||
setName("");
|
||||
setEquipmentType("");
|
||||
setSupplierId("");
|
||||
setDepartmentId("");
|
||||
setLocationId("");
|
||||
setStartDate(today.toISOString().slice(0, 10));
|
||||
setExpectedReturnDate(plus14.toISOString().slice(0, 10));
|
||||
setRemarks("");
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
const deptLocations = locations.filter(
|
||||
(l) => !departmentId || l.department_id === Number(departmentId)
|
||||
);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
equipment_type: equipmentType.trim(),
|
||||
supplier_id: Number(supplierId),
|
||||
department_id: Number(departmentId),
|
||||
location_id: locationId ? Number(locationId) : null,
|
||||
start_date: startDate,
|
||||
expected_return_date: expectedReturnDate,
|
||||
remarks: remarks.trim() || null,
|
||||
};
|
||||
if (editing) {
|
||||
await demoEquipmentApi.update(editing.id, payload);
|
||||
} else {
|
||||
await demoEquipmentApi.create(payload);
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save demo equipment.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Demo Equipment — ${editing.name}` : "Log Demo Equipment"}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Name *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Portable Ultrasound Demo Unit"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Equipment Type / Model *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={equipmentType}
|
||||
onChange={(e) => setEquipmentType(e.target.value)}
|
||||
placeholder="e.g. Diagnostic Imaging"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Supplier *</label>
|
||||
<select
|
||||
required
|
||||
value={supplierId}
|
||||
onChange={(e) => setSupplierId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select supplier...</option>
|
||||
{suppliers.map((s) => (
|
||||
<option key={s.id} value={String(s.id)}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select
|
||||
required
|
||||
value={departmentId}
|
||||
onChange={(e) => {
|
||||
setDepartmentId(e.target.value);
|
||||
setLocationId("");
|
||||
}}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Location</label>
|
||||
<select
|
||||
value={locationId}
|
||||
onChange={(e) => setLocationId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select location...</option>
|
||||
{deptLocations.map((l) => (
|
||||
<option key={l.id} value={String(l.id)}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div />
|
||||
<div>
|
||||
<label className={labelCls}>Start Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Expected Return Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={expectedReturnDate}
|
||||
onChange={(e) => setExpectedReturnDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Changes" : "Log Demo Equipment"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function ReturnDemoModal({
|
||||
open,
|
||||
onClose,
|
||||
item,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
item: DemoEquipmentItem | null;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [actualReturnDate, setActualReturnDate] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setActualReturnDate(new Date().toISOString().slice(0, 10));
|
||||
setRemarks(item?.remarks ?? "");
|
||||
setError(null);
|
||||
}, [open, item]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!item) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await demoEquipmentApi.markReturned(item.id, {
|
||||
actual_return_date: actualReturnDate,
|
||||
remarks: remarks.trim() || null,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["demo-equipment"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to mark returned.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={`Mark Returned — ${item?.name ?? ""}`}
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Actual Return Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={actualReturnDate}
|
||||
onChange={(e) => setActualReturnDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Return Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
placeholder="Condition, handover person, gate pass reference..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="success" loading={submitting}>
|
||||
Confirm Return
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Trash2,
|
||||
ShieldCheck,
|
||||
Search,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||
import { departmentsApi, vendorsApi } from "@/api/masters";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate, formatINR } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { ExpiryChip } from "@/components/StatusBadge";
|
||||
import { AssetPicker } from "@/components/AssetPicker";
|
||||
import { Attachments } from "@/components/Attachments";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
|
||||
const STATUS_CHIPS = [
|
||||
{ key: "", label: "All" },
|
||||
{ key: "active", label: "Active" },
|
||||
{ key: "expiring", label: "Expiring Soon" },
|
||||
{ key: "expired", label: "Expired" },
|
||||
];
|
||||
|
||||
export function InsurancePage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const isDeptUser = role === "department_user";
|
||||
const canManage = can(role, "manage_calibration_contracts");
|
||||
|
||||
const [statusFilter, setStatusFilter] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [insurerId, setInsurerId] = useState("");
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<InsuranceItem | null>(null);
|
||||
const [drawerAsset, setDrawerAsset] = useState<{
|
||||
assetId: number;
|
||||
label: string;
|
||||
} | null>(null);
|
||||
const [attachPolicy, setAttachPolicy] = useState<InsuranceItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
enabled: !isDeptUser,
|
||||
});
|
||||
|
||||
const vendorsQuery = useQuery({
|
||||
queryKey: ["vendors", "active-only"],
|
||||
queryFn: () => vendorsApi.list(false),
|
||||
});
|
||||
|
||||
const policiesQuery = useQuery({
|
||||
queryKey: ["insurance", q, departmentId, insurerId, statusFilter],
|
||||
queryFn: () =>
|
||||
insuranceApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||
insurer_id: insurerId ? Number(insurerId) : undefined,
|
||||
status: statusFilter || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => insuranceApi.remove(id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||
qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
},
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
const allVendors = vendorsQuery.data?.items ?? [];
|
||||
const insurers = allVendors.filter((v) => v.vendor_type === "insurer");
|
||||
const insurerOptions = insurers.length ? insurers : allVendors;
|
||||
|
||||
const columns: ColumnDef<InsuranceItem, unknown>[] = [
|
||||
{
|
||||
id: "asset",
|
||||
accessorFn: (r) => `${r.asset_code} ${r.asset_name}`,
|
||||
header: "Asset",
|
||||
cell: ({ row }) => (
|
||||
<Link to={`/assets/${row.original.asset_id}`} className="hover:underline">
|
||||
<div className="font-mono text-xs font-semibold text-[#1e3a8a]">
|
||||
{row.original.asset_code}
|
||||
</div>
|
||||
<div className="text-xs text-gray-800">{row.original.asset_name}</div>
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "insurer_name",
|
||||
header: "Insurer",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "policy_no",
|
||||
header: "Policy No",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="font-mono text-xs font-medium">{String(getValue())}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: "Start",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "end_date",
|
||||
header: "End",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap">{formatDate(getValue() as string)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "coverage_amount",
|
||||
header: "Coverage",
|
||||
cell: ({ getValue }) => formatINR(getValue() as number | null),
|
||||
},
|
||||
{
|
||||
id: "expiry",
|
||||
accessorFn: (r) => r.days_to_expiry,
|
||||
header: "Status",
|
||||
cell: ({ row }) => (
|
||||
<ExpiryChip
|
||||
daysToExpiry={row.original.days_to_expiry}
|
||||
status={row.original.status}
|
||||
severity={row.original.severity}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: "Docs",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setAttachPolicy(row.original)}
|
||||
title="View or upload policy certificates"
|
||||
>
|
||||
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||
<span className="text-xs">{row.original.attachment_count}</span>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
setDrawerAsset({
|
||||
assetId: row.original.asset_id,
|
||||
label: `${row.original.asset_code} — ${row.original.asset_name}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
<ShieldCheck className="h-3.5 w-3.5 mr-1" />
|
||||
Drawer
|
||||
</Button>
|
||||
{canManage && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditing(row.original);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
aria-label={`Edit policy ${row.original.policy_no}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-red-600 hover:text-red-700"
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete policy ${row.original.policy_no}?`)) {
|
||||
deleteMutation.mutate(row.original.id);
|
||||
}
|
||||
}}
|
||||
aria-label={`Delete policy ${row.original.policy_no}`}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Asset Insurance</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Track insurance policies, coverage amounts, expiry alerts, and policy certificates
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setFormOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Add Insurance Policy
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 space-y-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{STATUS_CHIPS.map((chip) => (
|
||||
<button
|
||||
key={chip.key}
|
||||
type="button"
|
||||
onClick={() => setStatusFilter(chip.key)}
|
||||
className={`px-3 py-1 rounded-full text-xs font-medium border transition-colors ${
|
||||
statusFilter === chip.key
|
||||
? "bg-[#1e3a8a] text-white border-[#1e3a8a]"
|
||||
: "bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100"
|
||||
}`}
|
||||
>
|
||||
{chip.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2.5">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search asset code, name, policy no..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isDeptUser && (
|
||||
<select
|
||||
value={departmentId}
|
||||
onChange={(e) => setDepartmentId(e.target.value)}
|
||||
aria-label="Filter by Department"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Departments</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
|
||||
<select
|
||||
value={insurerId}
|
||||
onChange={(e) => setInsurerId(e.target.value)}
|
||||
aria-label="Filter by Insurer"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Insurers</option>
|
||||
{insurerOptions.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={policiesQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={policiesQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter insurance policies..."
|
||||
exportFilename="insurance-policies"
|
||||
emptyMessage="No insurance policies match the selected filters."
|
||||
/>
|
||||
|
||||
<InsuranceFormModal
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
editing={editing}
|
||||
insurers={insurerOptions}
|
||||
/>
|
||||
|
||||
<InsuranceDrawer
|
||||
open={Boolean(drawerAsset)}
|
||||
onClose={() => setDrawerAsset(null)}
|
||||
assetId={drawerAsset?.assetId ?? null}
|
||||
assetLabel={drawerAsset?.label}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(attachPolicy)}
|
||||
onOpenChange={(o) => !o && setAttachPolicy(null)}
|
||||
title={`Policy Documents — ${attachPolicy?.policy_no ?? ""}`}
|
||||
className="max-w-xl"
|
||||
>
|
||||
{attachPolicy && (
|
||||
<Attachments
|
||||
entityType="insurance"
|
||||
entityId={attachPolicy.id}
|
||||
canUpload={canManage}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InsuranceFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
insurers,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: InsuranceItem | null;
|
||||
insurers: Array<{ id: number; name: string }>;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
|
||||
const [insurerId, setInsurerId] = useState("");
|
||||
const [policyNo, setPolicyNo] = useState("");
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [coverageAmount, setCoverageAmount] = useState("");
|
||||
const [remarks, setRemarks] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
if (editing) {
|
||||
setInsurerId(String(editing.insurer_id));
|
||||
setPolicyNo(editing.policy_no);
|
||||
setStartDate(editing.start_date);
|
||||
setEndDate(editing.end_date);
|
||||
setCoverageAmount(
|
||||
editing.coverage_amount != null ? String(editing.coverage_amount) : ""
|
||||
);
|
||||
setRemarks(editing.remarks ?? "");
|
||||
assetsApi
|
||||
.get(editing.asset_id)
|
||||
.then((a) =>
|
||||
setSelectedAsset({
|
||||
...a,
|
||||
contract_summary: a.contract_type ?? "None",
|
||||
insurance_summary: a.insurance_status,
|
||||
})
|
||||
)
|
||||
.catch(() => setSelectedAsset(null));
|
||||
} else {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const nextYear = new Date();
|
||||
nextYear.setFullYear(nextYear.getFullYear() + 1);
|
||||
setSelectedAsset(null);
|
||||
setInsurerId("");
|
||||
setPolicyNo("");
|
||||
setStartDate(today);
|
||||
setEndDate(nextYear.toISOString().slice(0, 10));
|
||||
setCoverageAmount("");
|
||||
setRemarks("");
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!editing && !selectedAsset) {
|
||||
setError("Please select an asset.");
|
||||
return;
|
||||
}
|
||||
if (!insurerId) {
|
||||
setError("Please select an insurer.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const payload = {
|
||||
insurer_id: Number(insurerId),
|
||||
policy_no: policyNo.trim(),
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
coverage_amount: coverageAmount.trim() !== "" ? Number(coverageAmount) : null,
|
||||
remarks: remarks.trim() || null,
|
||||
};
|
||||
if (editing) {
|
||||
await insuranceApi.update(editing.id, payload);
|
||||
} else {
|
||||
await insuranceApi.create({
|
||||
asset_id: selectedAsset!.id,
|
||||
...payload,
|
||||
});
|
||||
}
|
||||
await qc.invalidateQueries({ queryKey: ["insurance"] });
|
||||
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save insurance policy.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? `Edit Policy — ${editing.policy_no}` : "Add Insurance Policy"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className={labelCls}>Asset *</label>
|
||||
<AssetPicker
|
||||
selectedAsset={selectedAsset}
|
||||
onSelect={setSelectedAsset}
|
||||
disabled={Boolean(editing)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Insurer *</label>
|
||||
<select
|
||||
required
|
||||
value={insurerId}
|
||||
onChange={(e) => setInsurerId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select insurer...</option>
|
||||
{insurers.map((v) => (
|
||||
<option key={v.id} value={String(v.id)}>
|
||||
{v.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Policy Number *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={policyNo}
|
||||
onChange={(e) => setPolicyNo(e.target.value)}
|
||||
placeholder="e.g. POL-MED-2026-001"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Start Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>End Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Coverage Amount (INR)</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step="any"
|
||||
value={coverageAmount}
|
||||
onChange={(e) => setCoverageAmount(e.target.value)}
|
||||
placeholder="e.g. 500000"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Remarks</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
value={remarks}
|
||||
onChange={(e) => setRemarks(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Changes" : "Create Policy"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import {
|
||||
Plus,
|
||||
Pencil,
|
||||
AlertTriangle,
|
||||
Search,
|
||||
AlertCircle,
|
||||
CheckSquare,
|
||||
} from "lucide-react";
|
||||
import { visitsApi, type VisitItem } from "@/api/phase5";
|
||||
import { assetsApi } from "@/api/assets";
|
||||
import { departmentsApi } from "@/api/masters";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { can } from "@/lib/permissions";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { DataTable } from "@/components/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { CallStatusBadge } from "@/components/StatusBadge";
|
||||
import { RaiseComplaintModal } from "@/components/RaiseComplaintModal";
|
||||
|
||||
const inputCls =
|
||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||
|
||||
export function VisitsPage() {
|
||||
const qc = useQueryClient();
|
||||
const role = useAuthStore((s) => s.user?.role);
|
||||
const canManage = can(role, "manage_visits");
|
||||
|
||||
const [q, setQ] = useState("");
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
|
||||
const [visitModalOpen, setVisitModalOpen] = useState(false);
|
||||
const [editingVisit, setEditingVisit] = useState<VisitItem | null>(null);
|
||||
const [complaintVisitTarget, setComplaintVisitTarget] = useState<VisitItem | null>(null);
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", "active-only"],
|
||||
queryFn: () => departmentsApi.list(false),
|
||||
});
|
||||
|
||||
const visitsQuery = useQuery({
|
||||
queryKey: ["visits", q, departmentId, dateFrom, dateTo],
|
||||
queryFn: () =>
|
||||
visitsApi.list({
|
||||
q: q.trim() || undefined,
|
||||
department_id: departmentId ? Number(departmentId) : undefined,
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
page_size: 200,
|
||||
}),
|
||||
});
|
||||
|
||||
const departments = deptsQuery.data?.items ?? [];
|
||||
|
||||
const columns: ColumnDef<VisitItem, unknown>[] = [
|
||||
{
|
||||
accessorKey: "visit_date",
|
||||
header: "Visit Date",
|
||||
cell: ({ getValue }) => (
|
||||
<span className="whitespace-nowrap font-medium">
|
||||
{formatDate(getValue() as string)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "department_name",
|
||||
header: "Department",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "visited_by_name",
|
||||
header: "Visited By",
|
||||
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||
},
|
||||
{
|
||||
id: "assets",
|
||||
header: "Equipment Checked",
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => r.assets.map((a) => `${a.asset_code} ${a.name}`).join(" "),
|
||||
cell: ({ row }) =>
|
||||
row.original.assets.length === 0 ? (
|
||||
<span className="text-xs text-gray-400">None</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1 max-w-xs">
|
||||
{row.original.assets.map((a) => (
|
||||
<Link
|
||||
key={a.id}
|
||||
to={`/assets/${a.id}`}
|
||||
title={a.name}
|
||||
className="inline-flex items-center px-2 py-0.5 rounded bg-blue-50 text-[#1e3a8a] border border-blue-200 font-mono text-[11px] hover:bg-blue-100"
|
||||
>
|
||||
{a.asset_code}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "observations",
|
||||
header: "Observations",
|
||||
cell: ({ getValue }) => (
|
||||
<p className="text-xs text-gray-800 whitespace-pre-wrap max-w-sm">
|
||||
{String(getValue())}
|
||||
</p>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "complaints",
|
||||
header: "Linked Complaints",
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => r.complaints.map((c) => c.complaint_no).join(" "),
|
||||
cell: ({ row }) =>
|
||||
row.original.complaints.length === 0 ? (
|
||||
<span className="text-xs text-gray-400">—</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1">
|
||||
{row.original.complaints.map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
to={`/complaints/${c.id}`}
|
||||
className="inline-flex items-center gap-1.5 text-xs hover:underline"
|
||||
>
|
||||
<span className="font-mono font-semibold text-[#1e3a8a]">
|
||||
{c.complaint_no}
|
||||
</span>
|
||||
<CallStatusBadge status={c.call_status} />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
...(canManage
|
||||
? [
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }: { row: { original: VisitItem } }) => (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setComplaintVisitTarget(row.original)}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5 mr-1 text-amber-600" />
|
||||
Raise Complaint
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditingVisit(row.original);
|
||||
setVisitModalOpen(true);
|
||||
}}
|
||||
aria-label={`Edit visit ${row.original.id}`}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
} satisfies ColumnDef<VisitItem, unknown>,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Department Visits</h1>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
Daily biomedical rounds, equipment checks, observations, and breakdown escalation
|
||||
</p>
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditingVisit(null);
|
||||
setVisitModalOpen(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Log Visit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-3.5 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2.5">
|
||||
<div className="relative lg:col-span-2">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search observations, department, visitor..."
|
||||
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={departmentId}
|
||||
onChange={(e) => setDepartmentId(e.target.value)}
|
||||
aria-label="Filter by Department"
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||
>
|
||||
<option value="">All Departments</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Visit Date From"
|
||||
value={dateFrom}
|
||||
onChange={(e) => setDateFrom(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
aria-label="Visit Date To"
|
||||
value={dateTo}
|
||||
onChange={(e) => setDateTo(e.target.value)}
|
||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
data={visitsQuery.data?.items ?? []}
|
||||
columns={columns}
|
||||
loading={visitsQuery.isLoading}
|
||||
globalFilterPlaceholder="Quick filter visits..."
|
||||
exportFilename="department-visits"
|
||||
emptyMessage="No department visits recorded yet."
|
||||
/>
|
||||
|
||||
{canManage && (
|
||||
<>
|
||||
<VisitFormModal
|
||||
open={visitModalOpen}
|
||||
onClose={() => setVisitModalOpen(false)}
|
||||
editing={editingVisit}
|
||||
departments={departments}
|
||||
onCreatedAndRaise={(created) => setComplaintVisitTarget(created)}
|
||||
/>
|
||||
|
||||
<RaiseComplaintModal
|
||||
open={Boolean(complaintVisitTarget)}
|
||||
onClose={() => setComplaintVisitTarget(null)}
|
||||
initialAssetId={complaintVisitTarget?.assets[0]?.id ?? null}
|
||||
initialDescription={complaintVisitTarget?.observations ?? ""}
|
||||
navigateOnCreate={false}
|
||||
onCreated={async (complaint) => {
|
||||
if (!complaintVisitTarget) return;
|
||||
await visitsApi.linkComplaint(complaintVisitTarget.id, complaint.id);
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VisitFormModal({
|
||||
open,
|
||||
onClose,
|
||||
editing,
|
||||
departments,
|
||||
onCreatedAndRaise,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
editing: VisitItem | null;
|
||||
departments: Array<{ id: number; name: string }>;
|
||||
onCreatedAndRaise: (visit: VisitItem) => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [departmentId, setDepartmentId] = useState("");
|
||||
const [visitDate, setVisitDate] = useState("");
|
||||
const [observations, setObservations] = useState("");
|
||||
const [selectedAssetIds, setSelectedAssetIds] = useState<number[]>([]);
|
||||
const [assetSearch, setAssetSearch] = useState("");
|
||||
const [raiseImmediately, setRaiseImmediately] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null);
|
||||
setAssetSearch("");
|
||||
setRaiseImmediately(false);
|
||||
if (editing) {
|
||||
setDepartmentId(String(editing.department_id));
|
||||
setVisitDate(editing.visit_date);
|
||||
setObservations(editing.observations);
|
||||
setSelectedAssetIds(editing.assets.map((a) => a.id));
|
||||
} else {
|
||||
setDepartmentId("");
|
||||
setVisitDate(new Date().toISOString().slice(0, 10));
|
||||
setObservations("");
|
||||
setSelectedAssetIds([]);
|
||||
}
|
||||
}, [open, editing]);
|
||||
|
||||
const deptAssetsQuery = useQuery({
|
||||
queryKey: ["assets", "visit-checklist", departmentId],
|
||||
queryFn: () =>
|
||||
assetsApi.lookup({
|
||||
department_id: departmentId ? Number(departmentId) : undefined,
|
||||
limit: 200,
|
||||
}),
|
||||
enabled: open && Boolean(departmentId),
|
||||
});
|
||||
|
||||
const filteredAssets = useMemo(() => {
|
||||
const list = deptAssetsQuery.data?.items ?? [];
|
||||
const term = assetSearch.trim().toLowerCase();
|
||||
if (!term) return list;
|
||||
return list.filter((a) =>
|
||||
`${a.asset_code} ${a.name} ${a.location_name ?? ""}`
|
||||
.toLowerCase()
|
||||
.includes(term)
|
||||
);
|
||||
}, [deptAssetsQuery.data?.items, assetSearch]);
|
||||
|
||||
function toggleAsset(id: number) {
|
||||
setSelectedAssetIds((prev) =>
|
||||
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!departmentId) {
|
||||
setError("Please select a department.");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (editing) {
|
||||
await visitsApi.update(editing.id, {
|
||||
department_id: Number(departmentId),
|
||||
visit_date: visitDate,
|
||||
observations: observations.trim(),
|
||||
asset_ids: selectedAssetIds,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
onClose();
|
||||
} else {
|
||||
const created = await visitsApi.create({
|
||||
department_id: Number(departmentId),
|
||||
visit_date: visitDate,
|
||||
observations: observations.trim(),
|
||||
asset_ids: selectedAssetIds,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||
onClose();
|
||||
if (raiseImmediately) {
|
||||
onCreatedAndRaise(created);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.detail : "Failed to save visit.");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={editing ? "Edit Department Visit" : "Log Department Visit"}
|
||||
className="max-w-2xl"
|
||||
>
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className={labelCls}>Department *</label>
|
||||
<select
|
||||
required
|
||||
value={departmentId}
|
||||
onChange={(e) => {
|
||||
setDepartmentId(e.target.value);
|
||||
if (!editing) setSelectedAssetIds([]);
|
||||
}}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">Select department...</option>
|
||||
{departments.map((d) => (
|
||||
<option key={d.id} value={String(d.id)}>
|
||||
{d.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>Visit Date *</label>
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={visitDate}
|
||||
onChange={(e) => setVisitDate(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<label className="text-sm font-medium text-gray-700 flex items-center gap-1.5">
|
||||
<CheckSquare className="h-4 w-4 text-[#1e3a8a]" />
|
||||
Equipment Checked ({selectedAssetIds.length} selected)
|
||||
</label>
|
||||
{departmentId && (
|
||||
<input
|
||||
type="text"
|
||||
value={assetSearch}
|
||||
onChange={(e) => setAssetSearch(e.target.value)}
|
||||
placeholder="Filter department equipment..."
|
||||
className="px-2.5 py-1 text-xs border border-gray-200 rounded-md w-52"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="max-h-44 overflow-y-auto border border-gray-200 rounded-md divide-y divide-gray-100 bg-gray-50/40">
|
||||
{!departmentId ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
Select a department to view its equipment checklist.
|
||||
</div>
|
||||
) : deptAssetsQuery.isLoading ? (
|
||||
<div className="p-4 text-center text-xs text-gray-500">
|
||||
Loading department equipment...
|
||||
</div>
|
||||
) : filteredAssets.length === 0 ? (
|
||||
<div className="p-4 text-center text-xs text-gray-400">
|
||||
No matching assets found in this department.
|
||||
</div>
|
||||
) : (
|
||||
filteredAssets.map((a) => (
|
||||
<label
|
||||
key={a.id}
|
||||
className="flex items-center justify-between gap-2 px-3 py-2 text-xs hover:bg-blue-50/50 cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedAssetIds.includes(a.id)}
|
||||
onChange={() => toggleAsset(a.id)}
|
||||
className="h-3.5 w-3.5 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
<span className="font-mono font-semibold text-[#1e3a8a]">
|
||||
{a.asset_code}
|
||||
</span>
|
||||
<span className="text-gray-800 truncate">{a.name}</span>
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[10px] shrink-0">
|
||||
{a.location_name || "—"}
|
||||
</Badge>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className={labelCls}>Observations *</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
required
|
||||
value={observations}
|
||||
onChange={(e) => setObservations(e.target.value)}
|
||||
placeholder="Round findings, preventive checks, nurse feedback, issues spotted..."
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!editing && (
|
||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={raiseImmediately}
|
||||
onChange={(e) => setRaiseImmediately(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||
/>
|
||||
Raise & link a complaint immediately from this observation
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" loading={submitting}>
|
||||
{editing ? "Save Visit" : raiseImmediately ? "Save & Raise Complaint" : "Save Visit"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -36,18 +36,6 @@ export const DashboardPage = () => (
|
||||
</div>
|
||||
</StubPage>
|
||||
);
|
||||
export const ContractsPage = () => (
|
||||
<StubPage title="Contracts & Warranty" phase={5} description="AMC/CMC contracts and warranty tracking." />
|
||||
);
|
||||
export const InsurancePage = () => (
|
||||
<StubPage title="Insurance" phase={5} description="Insurance policies with expiry alerts." />
|
||||
);
|
||||
export const DemoEquipmentPage = () => (
|
||||
<StubPage title="Demo Equipment Register" phase={5} description="Demo equipment tracking with overdue returns." />
|
||||
);
|
||||
export const VisitsPage = () => (
|
||||
<StubPage title="Department Visits" phase={5} description="Daily department visit reports." />
|
||||
);
|
||||
export const ReportsPage = () => (
|
||||
<StubPage title="Reports & Exports" phase={7} description="8 reports with Excel export." />
|
||||
);
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||
import { ContractsPage } from "@/pages/ContractsPage";
|
||||
import { DemoEquipmentPage } from "@/pages/DemoEquipmentPage";
|
||||
import {
|
||||
insuranceApi,
|
||||
contractsApi,
|
||||
warrantiesApi,
|
||||
demoEquipmentApi,
|
||||
type ContractItem,
|
||||
type DemoEquipmentItem,
|
||||
} from "@/api/phase5";
|
||||
import { attachmentsApi } from "@/api/attachments";
|
||||
import { departmentsApi, locationsApi, vendorsApi } from "@/api/masters";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
|
||||
function renderWithProviders(ui: React.ReactNode) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<MemoryRouter>{ui}</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Phase 5 Modules", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useAuthStore.setState({
|
||||
user: {
|
||||
id: 2,
|
||||
email: "bio@poona.org",
|
||||
name: "Biomed Engineer",
|
||||
role: "biomedical",
|
||||
department_id: null,
|
||||
department_name: null,
|
||||
is_active: true,
|
||||
},
|
||||
token: "test-token",
|
||||
});
|
||||
|
||||
vi.spyOn(departmentsApi, "list").mockResolvedValue({
|
||||
items: [{ id: 1, name: "ICU", code: "ICU", description: null, is_active: true }],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(locationsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(vendorsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(attachmentsApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("InsuranceDrawer renders policy details for an asset", async () => {
|
||||
vi.spyOn(insuranceApi, "list").mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
id: 10,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
insurer_id: 5,
|
||||
insurer_name: "New India Assurance",
|
||||
policy_no: "POL-MED-2026-001",
|
||||
start_date: "2026-01-01",
|
||||
end_date: "2026-12-31",
|
||||
coverage_amount: 850000,
|
||||
status: "expiring",
|
||||
severity: "yellow",
|
||||
days_to_expiry: 18,
|
||||
attachment_count: 1,
|
||||
remarks: "All risk cover",
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(
|
||||
<InsuranceDrawer
|
||||
open={true}
|
||||
onClose={vi.fn()}
|
||||
assetId={1}
|
||||
assetLabel="PHRC-ICU-0001 — ICU Ventilator"
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("POL-MED-2026-001")).toBeInTheDocument();
|
||||
expect(screen.getByText("New India Assurance")).toBeInTheDocument();
|
||||
expect(screen.getByText("18 days left")).toBeInTheDocument();
|
||||
expect(screen.getByText(/All risk cover/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("ContractsPage renders renewal history with Superseded badge on older contract", async () => {
|
||||
const activeContract: ContractItem = {
|
||||
id: 202,
|
||||
asset_id: 1,
|
||||
asset_code: "PHRC-ICU-0001",
|
||||
asset_name: "ICU Ventilator",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
contract_type: "CMC",
|
||||
provider_id: 3,
|
||||
provider_name: "MedTech Services",
|
||||
start_date: "2026-01-01",
|
||||
end_date: "2026-12-31",
|
||||
coverage_period_text: "1 Year",
|
||||
renewed_from_id: 201,
|
||||
is_superseded: false,
|
||||
status: "active",
|
||||
severity: "ok",
|
||||
days_to_expiry: 120,
|
||||
attachment_count: 0,
|
||||
remarks: "Renewed CMC",
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
const oldSupersededContract: ContractItem = {
|
||||
...activeContract,
|
||||
id: 201,
|
||||
contract_type: "AMC",
|
||||
start_date: "2025-01-01",
|
||||
end_date: "2025-12-31",
|
||||
renewed_from_id: null,
|
||||
is_superseded: true,
|
||||
status: "superseded",
|
||||
severity: "ok",
|
||||
days_to_expiry: -30,
|
||||
remarks: "Initial AMC",
|
||||
};
|
||||
|
||||
vi.spyOn(contractsApi, "list").mockResolvedValue({
|
||||
items: [activeContract],
|
||||
total: 1,
|
||||
});
|
||||
vi.spyOn(warrantiesApi, "list").mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
});
|
||||
vi.spyOn(contractsApi, "history").mockResolvedValue({
|
||||
items: [activeContract, oldSupersededContract],
|
||||
});
|
||||
|
||||
renderWithProviders(<ContractsPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("PHRC-ICU-0001")).toBeInTheDocument();
|
||||
expect(screen.getByText("MedTech Services")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const historyBtn = screen.getByRole("button", { name: /History/i });
|
||||
fireEvent.click(historyBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/Contract Renewal History — PHRC-ICU-0001/i)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Superseded")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Renewed from #201/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("DemoEquipmentPage highlights overdue returns", async () => {
|
||||
const overdueItem: DemoEquipmentItem = {
|
||||
id: 301,
|
||||
name: "Portable Ultrasound Demo",
|
||||
equipment_type: "Imaging",
|
||||
supplier_id: 4,
|
||||
supplier_name: "MedEquip India",
|
||||
department_id: 1,
|
||||
department_name: "ICU",
|
||||
location_id: null,
|
||||
location_name: "ICU Bay 2",
|
||||
start_date: "2026-10-01",
|
||||
expected_return_date: "2026-10-15",
|
||||
actual_return_date: null,
|
||||
status: "overdue_return",
|
||||
severity: "red",
|
||||
days_remaining: -5,
|
||||
attachment_count: 0,
|
||||
remarks: "Pending pickup",
|
||||
created_at: "2026-10-01T00:00:00Z",
|
||||
};
|
||||
|
||||
vi.spyOn(demoEquipmentApi, "list").mockResolvedValue({
|
||||
items: [overdueItem],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
renderWithProviders(<DemoEquipmentPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Portable Ultrasound Demo")).toBeInTheDocument();
|
||||
expect(screen.getByText("Overdue by 5d")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /^Return$/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/calibrationmodals.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/pmpage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/pm-page.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||
Reference in New Issue
Block a user