phase-3: breakdown and complaint register with calculations and permissions

This commit is contained in:
Atharv1705
2026-11-12 12:54:21 +05:30
parent ee437e3adf
commit 905f6735a7
29 changed files with 3505 additions and 26 deletions
+2 -1
View File
@@ -58,12 +58,13 @@ cd backend
| mgmt@poona.demo | Demo@123 | Management |
| coord@poona.demo | Demo@123 | Coordinator |
## What exists now (Phase 2)
## What exists now (Phase 3)
- 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)
- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`)
- Asset Register (`/assets` & `/assets/:id`): full CRUD with duplicate asset code check (`409`), department scoping, coordinator field-level edit restrictions, 8-tab Asset Detail Overview, and audit logging
- 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)
- 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
+2 -1
View File
@@ -7,7 +7,7 @@ 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, health, masters, settings, users
from .routers import assets, attachments, auth, complaints, health, masters, settings, users
from .services.settings_service import ensure_default_settings
logging.basicConfig(
@@ -62,3 +62,4 @@ app.include_router(masters.router, prefix="/api")
app.include_router(users.router, prefix="/api")
app.include_router(assets.router, prefix="/api")
app.include_router(attachments.router, prefix="/api")
app.include_router(complaints.router, prefix="/api")
+1
View File
@@ -19,6 +19,7 @@ class Complaint(Base):
registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
registered_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
+11 -2
View File
@@ -1,3 +1,12 @@
from . import assets, attachments, auth, health, masters, settings, users
from . import assets, attachments, auth, complaints, health, masters, settings, users
__all__ = ["assets", "attachments", "auth", "health", "masters", "settings", "users"]
__all__ = [
"assets",
"attachments",
"auth",
"complaints",
"health",
"masters",
"settings",
"users",
]
+769
View File
@@ -0,0 +1,769 @@
from datetime import date, datetime, time, timedelta, timezone
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, 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 KOLKATA, utc_now
from ..models import Asset, Complaint, ComplaintEvent, User
from ..schemas.complaints import (
ComplaintAssignIn,
ComplaintAttendIn,
ComplaintCloseIn,
ComplaintCorrectTimestampIn,
ComplaintCreate,
ComplaintEventListOut,
ComplaintEventOut,
ComplaintListOut,
ComplaintOut,
ComplaintReopenIn,
ComplaintRestoreIn,
ComplaintUpdate,
)
from ..services.audit import log_audit
from ..services.calculations import (
compute_ce_response_time_minutes,
compute_downtime_minutes,
compute_response_time_minutes,
)
from ..services.numbering import generate_complaint_no
from ..services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role
from ..services.settings_service import get_demo_as_of_date, get_setting_value
router = APIRouter(prefix="/complaints", tags=["complaints"])
DEPT_USER_EDITABLE_FIELDS = {"description", "breakdown_details", "notes"}
def _norm_utc(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def _effective_now_utc(db: Session) -> datetime:
demo_str = get_demo_as_of_date(db)
if demo_str:
demo_d = date.fromisoformat(demo_str)
real_now_ist = datetime.now(KOLKATA)
if demo_d > real_now_ist.date():
local_dt = KOLKATA.localize(datetime.combine(demo_d, time(23, 59, 59)))
else:
local_dt = KOLKATA.localize(datetime.combine(demo_d, real_now_ist.time()))
return local_dt.astimezone(timezone.utc)
return utc_now()
def _complaint_settings(db: Session) -> tuple[str, str]:
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
response_start = str(get_setting_value(db, "response_start", "registered_at"))
return milestone, response_start
def _load_user_names(db: Session, complaints: list[Complaint]) -> dict[int, str]:
ids: set[int] = set()
for c in complaints:
for uid in (
c.registered_by_id,
c.received_by_id,
c.assigned_to_id,
c.attended_by_id,
c.closed_by_id,
):
if uid is not None:
ids.add(uid)
if not ids:
return {}
return {
u.id: u.name
for u in db.query(User.id, User.name).filter(User.id.in_(ids)).all()
}
def _to_complaint_out(
c: Complaint,
user_names: dict[int, str],
milestone: str,
response_start: str,
now_utc: datetime,
) -> ComplaintOut:
reg_at = _norm_utc(c.registered_at)
recv_at = _norm_utc(c.received_at)
asg_at = _norm_utc(c.assigned_at)
att_at = _norm_utc(c.attended_at)
rst_at = _norm_utc(c.restored_at)
cls_at = _norm_utc(c.closed_at)
ce_at = _norm_utc(c.ce_attended_at)
upd_at = _norm_utc(c.updated_at)
resp_min = compute_response_time_minutes(reg_at, recv_at, att_at, response_start=response_start)
dt_min, is_ongoing = compute_downtime_minutes(
reg_at, att_at, rst_at, cls_at, milestone=milestone, now_utc=now_utc
)
ce_min = compute_ce_response_time_minutes(reg_at, ce_at)
asset = c.asset
return ComplaintOut(
id=c.id,
complaint_no=c.complaint_no,
asset_id=c.asset_id,
asset_code=asset.asset_code,
asset_name=asset.name,
asset_status=asset.status,
department_id=asset.department_id,
department_name=asset.department.name if asset.department else None,
location_name=asset.location.name if asset.location else None,
description=c.description,
breakdown_details=c.breakdown_details,
priority=c.priority,
notes=c.notes,
registered_at=reg_at,
registered_by_id=c.registered_by_id,
registered_by_name=user_names.get(c.registered_by_id),
received_by_id=c.received_by_id,
received_by_name=user_names.get(c.received_by_id),
received_at=recv_at,
assigned_to_id=c.assigned_to_id,
assigned_to_name=user_names.get(c.assigned_to_id) if c.assigned_to_id else None,
assigned_at=asg_at,
attended_by_id=c.attended_by_id,
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
attended_at=att_at,
restored_at=rst_at,
closed_by_id=c.closed_by_id,
closed_by_name=user_names.get(c.closed_by_id) if c.closed_by_id else None,
closed_at=cls_at,
call_status=c.call_status,
closure_remarks=c.closure_remarks,
action_taken=c.action_taken,
root_cause=c.root_cause,
corrective_action=c.corrective_action,
lessons_learned=c.lessons_learned,
ce_name=c.ce_name,
ce_attended_at=ce_at,
ce_action_taken=c.ce_action_taken,
spare_required=c.spare_required,
spare_details=c.spare_details,
spare_cost_estimate=c.spare_cost_estimate,
response_time_minutes=resp_min,
downtime_minutes=dt_min,
downtime_is_ongoing=is_ongoing,
downtime_end_milestone=milestone,
response_start_setting=response_start,
ce_response_time_minutes=ce_min,
updated_at=upd_at,
)
def _load_complaint_or_404(db: Session, complaint_id: int) -> Complaint:
comp = (
db.query(Complaint)
.options(
joinedload(Complaint.asset).joinedload(Asset.department),
joinedload(Complaint.asset).joinedload(Asset.location),
)
.filter(Complaint.id == complaint_id)
.first()
)
if comp is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Complaint not found.")
return comp
def _check_complaint_visibility(comp: Complaint, user: User) -> None:
if user.role == Role.department_user.value and comp.asset.department_id != user.department_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Access denied for another department's complaint.",
)
def _serialize_one(db: Session, comp: Complaint) -> ComplaintOut:
user_names = _load_user_names(db, [comp])
milestone, response_start = _complaint_settings(db)
now_utc = _effective_now_utc(db)
return _to_complaint_out(comp, user_names, milestone, response_start, now_utc)
def _sync_asset_status(db: Session, asset: Asset, exclude_complaint_id: int, require_unrestored: bool) -> None:
if asset.status != "under_repair":
return
q = db.query(Complaint.id).filter(
Complaint.asset_id == asset.id,
Complaint.id != exclude_complaint_id,
Complaint.priority == "critical",
Complaint.call_status != "closed",
)
if require_unrestored:
q = q.filter(Complaint.restored_at.is_(None))
if q.first() is None:
asset.status = "in_service"
@router.get("", response_model=ComplaintListOut)
def list_complaints(
q: Optional[str] = None,
department_id: Optional[int] = None,
asset_id: Optional[int] = None,
call_status: Optional[str] = None,
priority: Optional[str] = None,
assigned_to_id: Optional[int] = None,
closure_state: Optional[str] = None,
date_from: Optional[str] = None,
date_to: Optional[str] = None,
page: int = Query(1, ge=1),
page_size: int = Query(100, ge=0, le=500),
sort: str = "-registered_at",
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
query = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.options(
joinedload(Complaint.asset).joinedload(Asset.department),
joinedload(Complaint.asset).joinedload(Asset.location),
)
)
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(Complaint.asset_id == asset_id)
if call_status:
query = query.filter(Complaint.call_status == call_status)
if priority:
query = query.filter(Complaint.priority == priority)
if assigned_to_id is not None:
query = query.filter(Complaint.assigned_to_id == assigned_to_id)
if closure_state == "open_only":
query = query.filter(Complaint.call_status != "closed")
elif closure_state == "closed_only":
query = query.filter(Complaint.call_status == "closed")
if date_from:
try:
d_from = date.fromisoformat(date_from)
except ValueError:
raise HTTPException(status_code=422, detail="date_from must be YYYY-MM-DD.")
start_utc = KOLKATA.localize(datetime.combine(d_from, time(0, 0, 0))).astimezone(timezone.utc)
query = query.filter(Complaint.registered_at >= start_utc)
if date_to:
try:
d_to = date.fromisoformat(date_to)
except ValueError:
raise HTTPException(status_code=422, detail="date_to must be YYYY-MM-DD.")
end_utc = KOLKATA.localize(
datetime.combine(d_to + timedelta(days=1), time(0, 0, 0))
).astimezone(timezone.utc)
query = query.filter(Complaint.registered_at < end_utc)
if q and q.strip():
like = f"%{q.strip()}%"
query = query.filter(
or_(
Complaint.complaint_no.ilike(like),
Complaint.description.ilike(like),
Asset.asset_code.ilike(like),
Asset.name.ilike(like),
)
)
sort_desc = sort.startswith("-")
sort_key = sort.lstrip("-")
sort_col_map = {
"id": Complaint.id,
"complaint_no": Complaint.complaint_no,
"registered_at": Complaint.registered_at,
"priority": Complaint.priority,
"call_status": Complaint.call_status,
"closed_at": Complaint.closed_at,
}
col = sort_col_map.get(sort_key, Complaint.registered_at)
query = query.order_by(col.desc() if sort_desc else col.asc(), Complaint.id.desc())
total = query.count()
if page_size > 0:
query = query.offset((page - 1) * page_size).limit(page_size)
rows = query.all()
user_names = _load_user_names(db, rows)
milestone, response_start = _complaint_settings(db)
now_utc = _effective_now_utc(db)
items = [_to_complaint_out(c, user_names, milestone, response_start, now_utc) for c in rows]
return {"items": items, "total": total}
@router.post("", response_model=ComplaintOut, status_code=status.HTTP_201_CREATED)
def create_complaint(
payload: ComplaintCreate,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.department_user)),
):
asset = (
db.query(Asset)
.options(joinedload(Asset.department), joinedload(Asset.location))
.filter(Asset.id == payload.asset_id)
.first()
)
if asset is None:
raise HTTPException(status_code=404, detail="Asset not found.")
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
raise HTTPException(status_code=403, detail="Cannot raise complaint for another department's asset.")
recv_by_id = payload.received_by_id or current_user.id
if payload.received_by_id is not None:
if not db.query(User.id).filter(User.id == payload.received_by_id).first():
raise HTTPException(status_code=404, detail="Received-by user not found.")
reg_at = utc_now()
recv_at = _norm_utc(payload.received_at) if payload.received_at is not None else reg_at
prefix = str(get_setting_value(db, "complaint_no_prefix", "CMP"))
cno = generate_complaint_no(db, prefix, reg_at)
comp = Complaint(
complaint_no=cno,
asset_id=asset.id,
description=payload.description.strip(),
breakdown_details=payload.breakdown_details,
priority=payload.priority,
notes=payload.notes,
registered_at=reg_at,
registered_by_id=current_user.id,
received_by_id=recv_by_id,
received_at=recv_at,
call_status="open",
updated_by_id=current_user.id,
)
db.add(comp)
db.flush()
if payload.priority == "critical" and bool(
get_setting_value(db, "critical_complaint_sets_under_repair", True)
):
asset.status = "under_repair"
asset.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="registered",
from_value=None,
to_value="open",
by_user_id=current_user.id,
at=reg_at,
note=payload.notes,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="create",
changes={"complaint_no": cno, "asset_id": asset.id, "priority": payload.priority},
user_id=current_user.id,
)
db.commit()
loaded = _load_complaint_or_404(db, comp.id)
return _serialize_one(db, loaded)
@router.get("/{complaint_id}", response_model=ComplaintOut)
def get_complaint(
complaint_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
comp = _load_complaint_or_404(db, complaint_id)
_check_complaint_visibility(comp, current_user)
return _serialize_one(db, comp)
@router.get("/{complaint_id}/events", response_model=ComplaintEventListOut)
def get_complaint_events(
complaint_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
comp = _load_complaint_or_404(db, complaint_id)
_check_complaint_visibility(comp, current_user)
rows = (
db.query(ComplaintEvent)
.filter(ComplaintEvent.complaint_id == comp.id)
.order_by(ComplaintEvent.at.asc(), ComplaintEvent.id.asc())
.all()
)
uid_set = {r.by_user_id for r in rows}
user_names = (
{u.id: u.name for u in db.query(User.id, User.name).filter(User.id.in_(uid_set)).all()}
if uid_set
else {}
)
items = [
ComplaintEventOut(
id=r.id,
complaint_id=r.complaint_id,
event_type=r.event_type,
from_value=r.from_value,
to_value=r.to_value,
by_user_id=r.by_user_id,
by_user_name=user_names.get(r.by_user_id),
at=_norm_utc(r.at),
note=r.note,
)
for r in rows
]
return {"items": items, "total": len(items)}
@router.patch("/{complaint_id}", response_model=ComplaintOut)
def update_complaint(
complaint_id: int,
payload: ComplaintUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
comp = _load_complaint_or_404(db, complaint_id)
fields_sent = payload.model_fields_set
if RESTRICTED_COMPLAINT_FIELDS & fields_sent and current_user.role not in (
Role.system_admin.value,
Role.biomedical.value,
):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only Biomedical or System Admin can edit technical resolution fields.",
code="FORBIDDEN_TECHNICAL_FIELDS",
)
if current_user.role in (Role.management.value, Role.coordinator.value):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You do not have permission to edit complaints.",
code="FORBIDDEN",
)
if current_user.role == Role.department_user.value:
_check_complaint_visibility(comp, current_user)
if comp.call_status == "closed":
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Closed complaints cannot be edited by department users.",
code="FORBIDDEN",
)
if not fields_sent.issubset(DEPT_USER_EDITABLE_FIELDS):
raise CodedHTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Department users can only edit description, breakdown_details, and notes.",
code="FORBIDDEN",
)
data = payload.model_dump(exclude_unset=True)
if "description" in data and data["description"] is not None:
data["description"] = data["description"].strip()
if "ce_attended_at" in data and data["ce_attended_at"] is not None:
data["ce_attended_at"] = _norm_utc(data["ce_attended_at"])
changes: dict[str, dict[str, Any]] = {}
for k, v in data.items():
old_val = getattr(comp, k)
if isinstance(old_val, datetime):
old_val = _norm_utc(old_val)
if old_val != v:
changes[k] = {"from": old_val, "to": v}
setattr(comp, k, v)
comp.updated_by_id = current_user.id
if changes:
now = utc_now()
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="field_edited",
from_value=None,
to_value=", ".join(sorted(changes.keys())),
by_user_id=current_user.id,
at=now,
note=f"Updated fields: {', '.join(sorted(changes.keys()))}",
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="update",
changes=changes,
user_id=current_user.id,
)
db.commit()
loaded = _load_complaint_or_404(db, comp.id)
return _serialize_one(db, loaded)
@router.post("/{complaint_id}/assign", response_model=ComplaintOut)
def assign_complaint(
complaint_id: int,
payload: ComplaintAssignIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
if assignee is None:
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
old_name: Optional[str] = None
event_type = "assigned"
if comp.assigned_to_id is not None:
event_type = "reassigned"
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
now = utc_now()
comp.assigned_to_id = assignee.id
comp.assigned_at = now
if comp.call_status == "open":
comp.call_status = "in_progress"
comp.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type=event_type,
from_value=old_name,
to_value=assignee.name,
by_user_id=current_user.id,
at=now,
note=payload.note,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action=event_type,
changes={"assigned_to_id": assignee.id, "note": payload.note},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/attend", response_model=ComplaintOut)
def attend_complaint(
complaint_id: int,
payload: ComplaintAttendIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
att_uid = payload.attended_by_id or current_user.id
att_user = db.query(User).filter(User.id == att_uid).first()
if att_user is None:
raise HTTPException(status_code=404, detail="Attending user not found.")
now = utc_now()
prev_status = comp.call_status
comp.attended_by_id = att_user.id
comp.attended_at = now
if comp.call_status == "open":
comp.call_status = "in_progress"
comp.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="attended",
from_value=prev_status,
to_value=comp.call_status,
by_user_id=current_user.id,
at=now,
note=payload.note or f"Attended by {att_user.name}",
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="attend",
changes={"attended_by_id": att_user.id},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/restore", response_model=ComplaintOut)
def restore_complaint(
complaint_id: int,
payload: ComplaintRestoreIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
now = utc_now()
comp.restored_at = now
comp.updated_by_id = current_user.id
_sync_asset_status(db, comp.asset, exclude_complaint_id=comp.id, require_unrestored=True)
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="restored",
from_value=None,
to_value=now.isoformat(),
by_user_id=current_user.id,
at=now,
note=payload.note,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="restore",
changes={"restored_at": now.isoformat()},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/close", response_model=ComplaintOut)
def close_complaint(
complaint_id: int,
payload: ComplaintCloseIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
now = utc_now()
prev_status = comp.call_status
comp.closed_by_id = current_user.id
comp.closed_at = now
if payload.closure_remarks is not None:
comp.closure_remarks = payload.closure_remarks
comp.call_status = "closed"
comp.updated_by_id = current_user.id
_sync_asset_status(db, comp.asset, exclude_complaint_id=comp.id, require_unrestored=False)
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="closed",
from_value=prev_status,
to_value="closed",
by_user_id=current_user.id,
at=now,
note=payload.closure_remarks,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="close",
changes={"call_status": "closed", "closure_remarks": payload.closure_remarks},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/reopen", response_model=ComplaintOut)
def reopen_complaint(
complaint_id: int,
payload: ComplaintReopenIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
):
comp = _load_complaint_or_404(db, complaint_id)
now = utc_now()
prev_status = comp.call_status
comp.closed_at = None
comp.closed_by_id = None
comp.call_status = "in_progress"
comp.updated_by_id = current_user.id
if comp.priority == "critical" and bool(
get_setting_value(db, "critical_complaint_sets_under_repair", True)
):
comp.asset.status = "under_repair"
comp.asset.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="reopened",
from_value=prev_status,
to_value="in_progress",
by_user_id=current_user.id,
at=now,
note=payload.reason,
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="reopen",
changes={"reason": payload.reason},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
@router.post("/{complaint_id}/correct-timestamp", response_model=ComplaintOut)
def correct_complaint_timestamp(
complaint_id: int,
payload: ComplaintCorrectTimestampIn,
db: Session = Depends(get_db),
current_user: User = Depends(require_roles(Role.system_admin)),
):
comp = _load_complaint_or_404(db, complaint_id)
now = utc_now()
old_val = _norm_utc(getattr(comp, payload.field))
new_val = _norm_utc(payload.new_value)
setattr(comp, payload.field, new_val)
comp.updated_by_id = current_user.id
from_str = old_val.isoformat() if old_val else None
to_str = new_val.isoformat() if new_val else None
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type="timestamp_corrected",
from_value=from_str,
to_value=to_str,
by_user_id=current_user.id,
at=now,
note=f"{payload.field}: {payload.reason}",
)
)
log_audit(
db,
entity_type="complaint",
entity_id=comp.id,
action="correct_timestamp",
changes={"field": payload.field, "from": from_str, "to": to_str, "reason": payload.reason},
user_id=current_user.id,
)
db.commit()
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
+2 -2
View File
@@ -57,7 +57,7 @@ def list_users(
return {"items": [_user_list_out(u) for u in items], "total": total}
@router.get("/lookup", response_model=list[UserLookupOut])
@router.get("/lookup", response_model=PaginatedOut[UserLookupOut])
def lookup_users(
db: Session = Depends(get_db),
_: User = Depends(get_current_user),
@@ -68,7 +68,7 @@ def lookup_users(
.order_by(User.name.asc())
.all()
)
return users
return {"items": users, "total": len(users)}
@router.post("", response_model=UserListOut, status_code=status.HTTP_201_CREATED)
+14
View File
@@ -9,6 +9,20 @@ from .assets import (
)
from .attachments import AttachmentListOut, AttachmentOut
from .auth import LoginRequest, TokenResponse, UserOut
from .complaints import (
ComplaintAssignIn,
ComplaintAttendIn,
ComplaintCloseIn,
ComplaintCorrectTimestampIn,
ComplaintCreate,
ComplaintEventListOut,
ComplaintEventOut,
ComplaintListOut,
ComplaintOut,
ComplaintReopenIn,
ComplaintRestoreIn,
ComplaintUpdate,
)
from .masters import (
CategoryCreate,
CategoryOut,
+147
View File
@@ -0,0 +1,147 @@
from datetime import datetime
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
ComplaintPriority = Literal["critical", "non_critical"]
TimestampField = Literal[
"registered_at",
"received_at",
"attended_at",
"restored_at",
"closed_at",
"ce_attended_at",
]
class ComplaintCreate(BaseModel):
asset_id: int
description: str = Field(..., min_length=1)
breakdown_details: Optional[str] = None
priority: ComplaintPriority = "non_critical"
notes: Optional[str] = None
received_by_id: Optional[int] = None
received_at: Optional[datetime] = None
class ComplaintUpdate(BaseModel):
description: Optional[str] = Field(None, min_length=1)
breakdown_details: Optional[str] = None
priority: Optional[ComplaintPriority] = None
notes: Optional[str] = None
closure_remarks: Optional[str] = None
# Restricted technical fields (system_admin / biomedical only)
action_taken: Optional[str] = None
root_cause: Optional[str] = None
corrective_action: Optional[str] = None
lessons_learned: Optional[str] = None
ce_name: Optional[str] = None
ce_attended_at: Optional[datetime] = None
ce_action_taken: Optional[str] = None
spare_required: Optional[bool] = None
spare_details: Optional[str] = None
spare_cost_estimate: Optional[float] = Field(None, ge=0)
class ComplaintAssignIn(BaseModel):
assigned_to_id: int
note: Optional[str] = None
class ComplaintAttendIn(BaseModel):
attended_by_id: Optional[int] = None
note: Optional[str] = None
class ComplaintRestoreIn(BaseModel):
note: Optional[str] = None
class ComplaintCloseIn(BaseModel):
closure_remarks: Optional[str] = None
class ComplaintReopenIn(BaseModel):
reason: str = Field(..., min_length=3)
class ComplaintCorrectTimestampIn(BaseModel):
field: TimestampField
new_value: datetime
reason: str = Field(..., min_length=3)
class ComplaintOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
complaint_no: str
asset_id: int
asset_code: str
asset_name: str
asset_status: str
department_id: int
department_name: Optional[str] = None
location_name: Optional[str] = None
description: str
breakdown_details: Optional[str] = None
priority: str
notes: Optional[str] = None
registered_at: datetime
registered_by_id: int
registered_by_name: Optional[str] = None
received_by_id: int
received_by_name: Optional[str] = None
received_at: Optional[datetime] = None
assigned_to_id: Optional[int] = None
assigned_to_name: Optional[str] = None
assigned_at: Optional[datetime] = None
attended_by_id: Optional[int] = None
attended_by_name: Optional[str] = None
attended_at: Optional[datetime] = None
restored_at: Optional[datetime] = None
closed_by_id: Optional[int] = None
closed_by_name: Optional[str] = None
closed_at: Optional[datetime] = None
call_status: str
closure_remarks: Optional[str] = None
action_taken: Optional[str] = None
root_cause: Optional[str] = None
corrective_action: Optional[str] = None
lessons_learned: Optional[str] = None
ce_name: Optional[str] = None
ce_attended_at: Optional[datetime] = None
ce_action_taken: Optional[str] = None
spare_required: bool
spare_details: Optional[str] = None
spare_cost_estimate: Optional[float] = None
response_time_minutes: Optional[int] = None
downtime_minutes: int
downtime_is_ongoing: bool
downtime_end_milestone: str
response_start_setting: str
ce_response_time_minutes: Optional[int] = None
updated_at: datetime
class ComplaintListOut(BaseModel):
items: list[ComplaintOut]
total: int
class ComplaintEventOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
complaint_id: int
event_type: str
from_value: Optional[str] = None
to_value: Optional[str] = None
by_user_id: int
by_user_name: Optional[str] = None
at: datetime
note: Optional[str] = None
class ComplaintEventListOut(BaseModel):
items: list[ComplaintEventOut]
total: int
+2
View File
@@ -618,6 +618,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
registered_at=reg_at,
registered_by_id=reg_user.id,
received_by_id=recv_user.id,
received_at=reg_at,
assigned_to_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
assigned_at=c_assigned_at,
attended_by_id=assigned_user.id if call_status in ("in_progress", "closed") else None,
@@ -795,6 +796,7 @@ def seed_database(db: Session, upload_dir: Path | None = None) -> dict[str, int]
def main():
t0 = pytime.perf_counter()
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
summary = seed_database(db)
+99 -1
View File
@@ -1,5 +1,12 @@
from datetime import date
from datetime import date, datetime, time, timedelta, timezone
from typing import Literal
from ..core.time_utils import KOLKATA, utc_now
def _ensure_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def alert_state(
@@ -60,3 +67,94 @@ def compute_schedule_status(
sev = "red" if days_left <= red_days else "yellow"
return ("due", sev)
return ("upcoming", "ok")
def compute_response_time_minutes(
registered_at: datetime,
received_at: datetime | None,
attended_at: datetime | None,
response_start: str = "registered_at",
) -> int | None:
"""Compute response time in whole minutes from registered_at or received_at to attended_at."""
if attended_at is None:
return None
reg_utc = _ensure_utc(registered_at)
att_utc = _ensure_utc(attended_at)
if response_start == "received_at" and received_at is not None:
start = _ensure_utc(received_at)
else:
start = reg_utc
return max(0, int((att_utc - start).total_seconds() // 60))
def compute_downtime_minutes(
registered_at: datetime,
attended_at: datetime | None,
restored_at: datetime | None,
closed_at: datetime | None,
milestone: str = "restored_at",
now_utc: datetime | None = None,
) -> tuple[int, bool]:
"""Compute (downtime_minutes, is_ongoing) using the configured end milestone."""
reg_utc = _ensure_utc(registered_at)
end_map = {
"attended_at": attended_at,
"restored_at": restored_at,
"closed_at": closed_at,
}
raw_end = end_map.get(milestone)
if raw_end is None:
is_ongoing = True
end_dt = _ensure_utc(now_utc) if now_utc is not None else utc_now()
else:
is_ongoing = False
end_dt = _ensure_utc(raw_end)
return max(0, int((end_dt - reg_utc).total_seconds() // 60)), is_ongoing
def compute_ce_response_time_minutes(
registered_at: datetime,
ce_attended_at: datetime | None,
) -> int | None:
"""Compute Company Engineer response time in whole minutes from registered_at."""
if ce_attended_at is None:
return None
reg_utc = _ensure_utc(registered_at)
ce_utc = _ensure_utc(ce_attended_at)
return max(0, int((ce_utc - reg_utc).total_seconds() // 60))
def clip_downtime_to_month(
start_utc: datetime,
end_utc: datetime,
year: int,
month: int,
) -> tuple[int, set[date]]:
"""Clip a UTC downtime interval to a calendar month in Asia/Kolkata.
Returns (minutes_in_month, distinct_kolkata_calendar_dates).
"""
win_start = KOLKATA.localize(datetime(year, month, 1, 0, 0, 0))
next_year, next_month = (year + 1, 1) if month == 12 else (year, month + 1)
win_end = KOLKATA.localize(datetime(next_year, next_month, 1, 0, 0, 0))
start_local = _ensure_utc(start_utc).astimezone(KOLKATA)
end_local = _ensure_utc(end_utc).astimezone(KOLKATA)
clipped_start = max(start_local, win_start)
clipped_end = min(end_local, win_end)
if clipped_end <= clipped_start:
return (0, set())
minutes = int((clipped_end - clipped_start).total_seconds() // 60)
distinct_dates: set[date] = set()
cur_day = clipped_start.date()
last_day = clipped_end.date()
while cur_day <= last_day:
day_start = KOLKATA.localize(datetime.combine(cur_day, time(0, 0, 0)))
day_end = day_start + timedelta(days=1)
if max(clipped_start, day_start) < min(clipped_end, day_end):
distinct_dates.add(cur_day)
cur_day += timedelta(days=1)
return (minutes, distinct_dates)
+24
View File
@@ -0,0 +1,24 @@
from datetime import datetime, timezone
from sqlalchemy.orm import Session
from ..core.time_utils import to_kolkata
from ..models.complaints import Complaint
def generate_complaint_no(db: Session, prefix: str, dt_utc: datetime) -> str:
dt_aware = dt_utc if dt_utc.tzinfo else dt_utc.replace(tzinfo=timezone.utc)
year = to_kolkata(dt_aware).year
base = f"{prefix}-{year}-"
existing = (
db.query(Complaint.complaint_no)
.filter(Complaint.complaint_no.like(f"{base}%"))
.all()
)
max_seq = 0
for (cno,) in existing:
if cno and cno.startswith(base):
suffix = cno[len(base) :]
if suffix.isdigit():
val = int(suffix)
if val > max_seq:
max_seq = val
return f"{base}{max_seq + 1:04d}"
-1
View File
@@ -81,7 +81,6 @@ CAPABILITIES: dict[Role, set[str]] = {
Role.coordinator: {
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"view_pm",
"manage_calibration_contracts",
+43 -3
View File
@@ -147,6 +147,46 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
"max": None,
"options": ["in_house", "outsourced"],
},
{
"key": "complaint_no_prefix",
"type": "str",
"default": "CMP",
"label": "Complaint Number Prefix",
"description": "Prefix used when generating sequential breakdown complaint numbers (e.g. CMP-2026-0001).",
"min": None,
"max": None,
"options": None,
},
{
"key": "critical_complaint_sets_under_repair",
"type": "bool",
"default": True,
"label": "Critical Complaint Marks Asset Under Repair",
"description": "Automatically set asset status to under_repair when a critical breakdown complaint is registered or reopened.",
"min": None,
"max": None,
"options": None,
},
{
"key": "response_start",
"type": "enum",
"default": "registered_at",
"label": "Response Time Start Milestone",
"description": "Timestamp used as the starting point for biomedical response time calculation.",
"min": None,
"max": None,
"options": ["registered_at", "received_at"],
},
{
"key": "downtime_end_milestone",
"type": "enum",
"default": "restored_at",
"label": "Downtime End Milestone",
"description": "Milestone timestamp that stops the equipment downtime clock.",
"min": None,
"max": None,
"options": ["attended_at", "restored_at", "closed_at"],
},
]
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
@@ -243,15 +283,15 @@ def ensure_default_settings(db: Session) -> None:
db.flush()
def get_setting_value(db: Session, key: str) -> Any:
def get_setting_value(db: Session, key: str, default: Any = None) -> Any:
spec = SETTINGS_BY_KEY.get(key)
row = db.query(Setting).filter(Setting.key == key).first()
if row is None:
return spec["default"] if spec else None
return spec["default"] if spec else default
try:
return json.loads(row.value_json)
except (ValueError, TypeError):
return spec["default"] if spec else None
return spec["default"] if spec else default
def get_demo_as_of_date(db: Session) -> str | None:
+83 -4
View File
@@ -1,9 +1,12 @@
import asyncio
import threading
import httpx
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.main import app
from app.core.db import get_db
from app.main import app
from app.models import Base
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
@@ -11,8 +14,81 @@ engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_threa
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine_test)
class _WaitSelector:
def __init__(self, event: threading.Event):
self._event = event
def select(self, timeout=None):
self._event.wait(timeout)
self._event.clear()
return []
def close(self):
pass
class _SocketFreeEventLoop(asyncio.BaseEventLoop):
"""Pure-Python asyncio loop using threading.Event instead of socketpair (works in Windows sandbox)."""
def __init__(self):
self._wake_event = threading.Event()
super().__init__()
self._selector = _WaitSelector(self._wake_event)
def _write_to_self(self):
self._wake_event.set()
def _process_events(self, event_list):
pass
def _close_self_pipe(self):
pass
def close(self):
super().close()
self._selector.close()
class SyncASGITestClient:
"""Synchronous HTTP test client backed by httpx.AsyncClient + ASGITransport."""
def __init__(self, asgi_app):
self._app = asgi_app
self._loop = _SocketFreeEventLoop()
self._lifespan_cm = asgi_app.router.lifespan_context(asgi_app)
self._loop.run_until_complete(self._lifespan_cm.__aenter__())
self._client = httpx.AsyncClient(
transport=httpx.ASGITransport(app=asgi_app),
base_url="http://testserver",
)
def request(self, method: str, url: str, **kwargs) -> httpx.Response:
return self._loop.run_until_complete(self._client.request(method, url, **kwargs))
def get(self, url: str, **kwargs) -> httpx.Response:
return self.request("GET", url, **kwargs)
def post(self, url: str, **kwargs) -> httpx.Response:
return self.request("POST", url, **kwargs)
def put(self, url: str, **kwargs) -> httpx.Response:
return self.request("PUT", url, **kwargs)
def patch(self, url: str, **kwargs) -> httpx.Response:
return self.request("PATCH", url, **kwargs)
def delete(self, url: str, **kwargs) -> httpx.Response:
return self.request("DELETE", url, **kwargs)
def close(self):
self._loop.run_until_complete(self._client.aclose())
self._loop.run_until_complete(self._lifespan_cm.__aexit__(None, None, None))
self._loop.close()
@pytest.fixture(scope="session")
def db():
Base.metadata.drop_all(bind=engine_test)
Base.metadata.create_all(bind=engine_test)
session = TestingSessionLocal()
yield session
@@ -29,6 +105,9 @@ def client(db):
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as c:
c = SyncASGITestClient(app)
try:
yield c
app.dependency_overrides.clear()
finally:
c.close()
app.dependency_overrides.clear()
+2 -1
View File
@@ -266,6 +266,7 @@ def test_permissions_matrix_all_roles():
# coordinator
assert has_capability(Role.coordinator, "manage_admin") is False
assert has_capability(Role.coordinator, "raise_complaint") is False
assert has_capability(Role.coordinator, "edit_asset_contracts_only") is True
assert has_capability(Role.coordinator, "handle_complaint") is True
assert has_capability(Role.coordinator, "edit_technical_fields") is False
@@ -284,7 +285,7 @@ def test_settings_validation_and_demo_date(client, db):
res = client.get("/api/settings", headers=headers)
assert res.status_code == 200
items = res.json()["items"]
assert len(items) == 14
assert len(items) >= 14
# Out of range int
bad_range = client.put(
+332
View File
@@ -0,0 +1,332 @@
from datetime import date, datetime, timedelta, timezone
import pytest
from app.core.time_utils import KOLKATA
from app.models import Asset, Complaint, Department, User
from app.seed.seed import seed_database
from app.services.calculations import (
clip_downtime_to_month,
compute_ce_response_time_minutes,
compute_downtime_minutes,
compute_response_time_minutes,
)
from app.services.numbering import generate_complaint_no
@pytest.fixture(scope="module", autouse=True)
def seeded_complaints_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("complaint_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 test_generate_complaint_no_and_custom_prefix(db):
dt = datetime(2026, 4, 15, 10, 0, tzinfo=timezone.utc)
# Seed created CMP-2026-0001..0030 (when run in 2026) or current year; test custom prefix cleanly
c1 = generate_complaint_no(db, "PHRC", dt)
assert c1 == "PHRC-2026-0001"
# Existing CMP prefix in current KOLKATA year increments sequentially
now_utc = datetime.now(timezone.utc)
cur_year = now_utc.astimezone(KOLKATA).year
next_cmp = generate_complaint_no(db, "CMP", now_utc)
assert next_cmp == f"CMP-{cur_year}-0031"
def test_response_time_and_downtime_calculations():
reg = datetime(2026, 5, 10, 8, 0, tzinfo=timezone.utc)
recv = datetime(2026, 5, 10, 8, 15, tzinfo=timezone.utc)
att = datetime(2026, 5, 10, 9, 0, tzinfo=timezone.utc)
rst = datetime(2026, 5, 10, 11, 30, tzinfo=timezone.utc)
cls = datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc)
ce_att = datetime(2026, 5, 10, 10, 0, tzinfo=timezone.utc)
now = datetime(2026, 5, 10, 13, 0, tzinfo=timezone.utc)
# Response time
assert compute_response_time_minutes(reg, recv, None, "registered_at") is None
assert compute_response_time_minutes(reg, recv, att, "registered_at") == 60
assert compute_response_time_minutes(reg, recv, att, "received_at") == 45
# CE response time
assert compute_ce_response_time_minutes(reg, None) is None
assert compute_ce_response_time_minutes(reg, ce_att) == 120
# Downtime milestones
assert compute_downtime_minutes(reg, att, rst, cls, "attended_at", now) == (60, False)
assert compute_downtime_minutes(reg, att, rst, cls, "restored_at", now) == (210, False)
assert compute_downtime_minutes(reg, att, rst, cls, "closed_at", now) == (240, False)
# Ongoing downtime when chosen milestone is None
assert compute_downtime_minutes(reg, att, None, None, "restored_at", now) == (300, True)
def test_clip_downtime_to_month_across_boundary():
# Jan 30 22:00 IST to Feb 02 04:00 IST
start_utc = KOLKATA.localize(datetime(2026, 1, 30, 22, 0, 0)).astimezone(timezone.utc)
end_utc = KOLKATA.localize(datetime(2026, 2, 2, 4, 0, 0)).astimezone(timezone.utc)
jan_mins, jan_days = clip_downtime_to_month(start_utc, end_utc, 2026, 1)
assert jan_mins == 26 * 60 # 2h on Jan 30 + 24h on Jan 31 = 1560 mins
assert jan_days == {date(2026, 1, 30), date(2026, 1, 31)}
feb_mins, feb_days = clip_downtime_to_month(start_utc, end_utc, 2026, 2)
assert feb_mins == 28 * 60 # 24h on Feb 1 + 4h on Feb 2 = 1680 mins
assert feb_days == {date(2026, 2, 1), date(2026, 2, 2)}
mar_mins, mar_days = clip_downtime_to_month(start_utc, end_utc, 2026, 3)
assert mar_mins == 0
assert mar_days == set()
def test_complaint_field_level_permissions(client, db):
dept_headers = _auth_headers(client, "dept@poona.demo")
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
coord_headers = _auth_headers(client, "coord@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
admin_headers = _auth_headers(client, "admin@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
ot = db.query(Department).filter(Department.code == "OT").first()
icu_cmp = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.filter(Asset.department_id == icu.id, Complaint.call_status != "closed")
.first()
)
ot_cmp = (
db.query(Complaint)
.join(Asset, Complaint.asset_id == Asset.id)
.filter(Asset.department_id == ot.id)
.first()
)
if icu_cmp is None:
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
r = client.post(
"/api/complaints",
headers=dept_headers,
json={"asset_id": icu_asset.id, "description": "Permission test issue", "priority": "non_critical"},
)
assert r.status_code == 201
icu_cmp_id = r.json()["id"]
else:
icu_cmp_id = icu_cmp.id
# Department scoping on list and detail
if ot_cmp is not None:
assert client.get(f"/api/complaints/{ot_cmp.id}", headers=dept_headers).status_code == 403
assert client.get(f"/api/complaints/{ot_cmp.id}/events", headers=dept_headers).status_code == 403
list_res = client.get("/api/complaints?page_size=200", headers=dept_headers)
assert list_res.status_code == 200
assert all(item["department_id"] == icu.id for item in list_res.json()["items"])
# Restricted technical fields rejected with 403 for dept_user, management, coordinator
for headers in (dept_headers, mgmt_headers, coord_headers):
for payload in (
{"action_taken": "Replaced PCB"},
{"root_cause": "Short circuit"},
{"spare_required": True, "spare_cost_estimate": 5000},
):
r = client.patch(f"/api/complaints/{icu_cmp_id}", headers=headers, json=payload)
assert r.status_code == 403
assert r.json()["code"] == "FORBIDDEN_TECHNICAL_FIELDS"
# Non-restricted edit by dept_user works on own non-closed complaint, fails for mgmt/coord
assert (
client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=dept_headers,
json={"notes": "Updated ward note"},
).status_code
== 200
)
assert (
client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=mgmt_headers,
json={"notes": "Mgmt edit"},
).status_code
== 403
)
assert (
client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=coord_headers,
json={"notes": "Coord edit"},
).status_code
== 403
)
# biomedical and system_admin succeed on technical fields
bio_patch = client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=bio_headers,
json={"action_taken": "Cleaned connector", "root_cause": "Loose cable"},
)
assert bio_patch.status_code == 200
assert bio_patch.json()["action_taken"] == "Cleaned connector"
admin_patch = client.patch(
f"/api/complaints/{icu_cmp_id}",
headers=admin_headers,
json={"corrective_action": "Secured latch"},
)
assert admin_patch.status_code == 200
assert admin_patch.json()["corrective_action"] == "Secured latch"
def test_full_complaint_workflow_and_asset_status_sync(client, db):
dept_headers = _auth_headers(client, "dept@poona.demo")
bio_headers = _auth_headers(client, "bio@poona.demo")
admin_headers = _auth_headers(client, "admin@poona.demo")
icu = db.query(Department).filter(Department.code == "ICU").first()
asset = db.query(Asset).filter(Asset.department_id == icu.id, Asset.status == "in_service").first()
assert asset is not None
bio1 = db.query(User).filter(User.email == "bio@poona.demo").first()
bio2 = db.query(User).filter(User.email == "vikram.shinde@poona.demo").first()
# 1. Dept user raises critical complaint -> asset becomes under_repair
create_res = client.post(
"/api/complaints",
headers=dept_headers,
json={
"asset_id": asset.id,
"description": "Ventilator pressure drop alarm",
"breakdown_details": "Alarm triggered during patient weaning",
"priority": "critical",
"notes": "Urgent ICU support needed",
},
)
assert create_res.status_code == 201, create_res.text
cmp_data = create_res.json()
cid = cmp_data["id"]
assert cmp_data["call_status"] == "open"
assert cmp_data["asset_status"] == "under_repair"
assert cmp_data["downtime_is_ongoing"] is True
# 2. Assign -> reassign (events logged)
asg1 = client.post(
f"/api/complaints/{cid}/assign",
headers=bio_headers,
json={"assigned_to_id": bio1.id, "note": "Initial assignment"},
)
assert asg1.status_code == 200
assert asg1.json()["call_status"] == "in_progress"
assert asg1.json()["assigned_to_id"] == bio1.id
asg2 = client.post(
f"/api/complaints/{cid}/assign",
headers=bio_headers,
json={"assigned_to_id": bio2.id, "note": "Escalated to senior bio"},
)
assert asg2.status_code == 200
assert asg2.json()["assigned_to_id"] == bio2.id
# 3. Attend -> response_time_minutes computed
att_res = client.post(
f"/api/complaints/{cid}/attend",
headers=bio_headers,
json={"attended_by_id": bio2.id, "note": "Reached ICU Bay"},
)
assert att_res.status_code == 200
assert att_res.json()["attended_at"] is not None
assert att_res.json()["response_time_minutes"] is not None
# 4. Edit technical / spare / CE fields
ce_time = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
tech_res = client.patch(
f"/api/complaints/{cid}",
headers=bio_headers,
json={
"action_taken": "Replaced inspiratory valve diaphragm",
"root_cause": "Diaphragm tear",
"corrective_action": "Replaced valve kit and ran leak test",
"lessons_learned": "Inspect diaphragm at every 6m PM",
"ce_name": "Mahesh Kulkarni (OEM)",
"ce_attended_at": ce_time,
"ce_action_taken": "Calibrated flow sensor post replacement",
"spare_required": True,
"spare_details": "Inspiratory valve diaphragm kit",
"spare_cost_estimate": 12500.0,
},
)
assert tech_res.status_code == 200
assert tech_res.json()["spare_required"] is True
assert tech_res.json()["ce_response_time_minutes"] is not None
# 5. Restore -> asset returns to in_service
rst_res = client.post(
f"/api/complaints/{cid}/restore",
headers=bio_headers,
json={"note": "Passed 30-min leak test"},
)
assert rst_res.status_code == 200
assert rst_res.json()["restored_at"] is not None
assert rst_res.json()["asset_status"] == "in_service"
assert rst_res.json()["downtime_is_ongoing"] is False
# 6. Close -> call_status closed
cls_res = client.post(
f"/api/complaints/{cid}/close",
headers=bio_headers,
json={"closure_remarks": "Handed over to ICU charge nurse"},
)
assert cls_res.status_code == 200
assert cls_res.json()["call_status"] == "closed"
assert cls_res.json()["closed_at"] is not None
assert cls_res.json()["asset_status"] == "in_service"
# 7. Reopen -> critical asset back to under_repair
reopen_res = client.post(
f"/api/complaints/{cid}/reopen",
headers=bio_headers,
json={"reason": "Alarm reappeared during shift change"},
)
assert reopen_res.status_code == 200
assert reopen_res.json()["call_status"] == "in_progress"
assert reopen_res.json()["closed_at"] is None
assert reopen_res.json()["asset_status"] == "under_repair"
# 8. Correct timestamp: biomedical -> 403, system_admin -> 200
new_reg = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
bio_ts = client.post(
f"/api/complaints/{cid}/correct-timestamp",
headers=bio_headers,
json={"field": "registered_at", "new_value": new_reg, "reason": "Late entry"},
)
assert bio_ts.status_code == 403
admin_ts = client.post(
f"/api/complaints/{cid}/correct-timestamp",
headers=admin_headers,
json={"field": "registered_at", "new_value": new_reg, "reason": "Logged after phone call"},
)
assert admin_ts.status_code == 200
assert admin_ts.json()["response_time_minutes"] >= 119
# 9. Verify events timeline
ev_res = client.get(f"/api/complaints/{cid}/events", headers=bio_headers)
assert ev_res.status_code == 200
events = ev_res.json()["items"]
event_types = [e["event_type"] for e in events]
assert event_types == [
"registered",
"assigned",
"reassigned",
"attended",
"field_edited",
"restored",
"closed",
"reopened",
"timestamp_corrected",
]
assert events[2]["from_value"] == bio1.name
assert events[2]["to_value"] == bio2.name
assert events[8]["note"] == "registered_at: Logged after phone call"
+3 -1
View File
@@ -9,9 +9,10 @@ import { MastersPage } from "@/pages/MastersPage";
import { SettingsPage } from "@/pages/SettingsPage";
import { AssetsPage } from "@/pages/AssetsPage";
import { AssetDetailPage } from "@/pages/AssetDetailPage";
import { ComplaintsPage } from "@/pages/ComplaintsPage";
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
import {
DashboardPage,
ComplaintsPage,
PMPage,
CalibrationPage,
ContractsPage,
@@ -84,6 +85,7 @@ function AppRoutes() {
<Route path="/assets" element={<AssetsPage />} />
<Route path="/assets/:id" element={<AssetDetailPage />} />
<Route path="/complaints" element={<ComplaintsPage />} />
<Route path="/complaints/:id" element={<ComplaintDetailPage />} />
<Route path="/pm" element={<PMPage />} />
<Route path="/calibration" element={<CalibrationPage />} />
<Route path="/contracts" element={<ContractsPage />} />
+153
View File
@@ -0,0 +1,153 @@
import { api } from "./client";
import type { AssetCriticality, AssetStatus } from "./assets";
export type CallStatus = "open" | "in_progress" | "closed";
export type TimestampField =
| "registered_at"
| "received_at"
| "attended_at"
| "restored_at"
| "closed_at"
| "ce_attended_at";
export interface ComplaintItem {
id: number;
complaint_no: string;
asset_id: number;
asset_code: string;
asset_name: string;
asset_status: AssetStatus | string;
department_id: number;
department_name: string | null;
location_name: string | null;
description: string;
breakdown_details: string | null;
priority: AssetCriticality | string;
notes: string | null;
registered_at: string;
registered_by_id: number;
registered_by_name: string | null;
received_by_id: number | null;
received_by_name: string | null;
received_at: string | null;
assigned_to_id: number | null;
assigned_to_name: string | null;
assigned_at: string | null;
attended_by_id: number | null;
attended_by_name: string | null;
attended_at: string | null;
restored_at: string | null;
closed_by_id: number | null;
closed_by_name: string | null;
closed_at: string | null;
call_status: CallStatus;
closure_remarks: string | null;
action_taken: string | null;
root_cause: string | null;
corrective_action: string | null;
lessons_learned: string | null;
ce_name: string | null;
ce_attended_at: string | null;
ce_action_taken: string | null;
spare_required: boolean;
spare_details: string | null;
spare_cost_estimate: number | null;
response_time_minutes: number | null;
downtime_minutes: number;
downtime_is_ongoing: boolean;
downtime_end_milestone: string;
response_start_setting: string;
ce_response_time_minutes: number | null;
updated_at: string;
}
export interface ComplaintEventItem {
id: number;
complaint_id: number;
event_type: string;
from_value: string | null;
to_value: string | null;
by_user_id: number | null;
by_user_name: string | null;
at: string;
note: string | null;
}
export interface ComplaintListParams {
q?: string;
department_id?: number;
asset_id?: number;
call_status?: CallStatus | "";
priority?: AssetCriticality | "";
assigned_to_id?: number;
closure_state?: "open_only" | "closed_only" | "";
date_from?: string;
date_to?: string;
page?: number;
page_size?: number;
}
export interface ComplaintCreatePayload {
asset_id: number;
description: string;
breakdown_details?: string | null;
priority: AssetCriticality;
notes?: string | null;
received_by_id?: number | null;
}
export interface ComplaintUpdatePayload {
description?: string;
breakdown_details?: string | null;
priority?: AssetCriticality;
notes?: string | null;
action_taken?: string | null;
root_cause?: string | null;
corrective_action?: string | null;
lessons_learned?: string | null;
ce_name?: string | null;
ce_attended_at?: string | null;
ce_action_taken?: string | null;
spare_required?: boolean;
spare_details?: string | null;
spare_cost_estimate?: number | null;
}
export const complaintsApi = {
list: (params: ComplaintListParams = {}) => {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
if (params.department_id) qs.set("department_id", String(params.department_id));
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
if (params.call_status) qs.set("call_status", params.call_status);
if (params.priority) qs.set("priority", params.priority);
if (params.assigned_to_id) qs.set("assigned_to_id", String(params.assigned_to_id));
if (params.closure_state) qs.set("closure_state", params.closure_state);
if (params.date_from) qs.set("date_from", params.date_from);
if (params.date_to) qs.set("date_to", params.date_to);
qs.set("page", String(params.page ?? 1));
qs.set("page_size", String(params.page_size ?? 200));
return api.get<{ items: ComplaintItem[]; total: number }>(`/complaints?${qs.toString()}`);
},
create: (data: ComplaintCreatePayload) => api.post<ComplaintItem>("/complaints", data),
get: (id: number) => api.get<ComplaintItem>(`/complaints/${id}`),
events: (id: number) =>
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
update: (id: number, data: ComplaintUpdatePayload) =>
api.patch<ComplaintItem>(`/complaints/${id}`, data),
assign: (id: number, data: { assigned_to_id: number; note?: string }) =>
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
restore: (id: number, data: { note?: string } = {}) =>
api.post<ComplaintItem>(`/complaints/${id}/restore`, data),
close: (id: number, data: { closure_remarks?: string } = {}) =>
api.post<ComplaintItem>(`/complaints/${id}/close`, data),
reopen: (id: number, data: { reason: string }) =>
api.post<ComplaintItem>(`/complaints/${id}/reopen`, data),
correctTimestamp: (
id: number,
data: { field: TimestampField; new_value: string; reason: string }
) => api.post<ComplaintItem>(`/complaints/${id}/correct-timestamp`, data),
};
+17
View File
@@ -154,3 +154,20 @@ export const usersApi = {
) => api.patch<MasterUser>(`/users/${id}`, data),
remove: (id: number) => api.delete<void>(`/users/${id}`),
};
export interface UserLookupItem {
id: number;
name: string;
role: Role;
department_id: number | null;
}
export async function fetchUsersLookup(): Promise<{ items: UserLookupItem[]; total: number }> {
const res = await api.get<UserLookupItem[] | { items: UserLookupItem[]; total: number }>(
"/users/lookup"
);
if (Array.isArray(res)) {
return { items: res, total: res.length };
}
return res;
}
@@ -25,6 +25,7 @@ interface DataTableProps<TData> {
emptyAction?: React.ReactNode;
globalFilterPlaceholder?: string;
onRowClick?: (row: TData) => void;
getRowClassName?: (row: TData) => string;
exportFilename?: string;
}
@@ -52,6 +53,7 @@ export function DataTable<TData>({
emptyAction,
globalFilterPlaceholder = "Search...",
onRowClick,
getRowClassName,
exportFilename = "export",
}: DataTableProps<TData>) {
const [sorting, setSorting] = useState<SortingState>([]);
@@ -203,6 +205,7 @@ export function DataTable<TData>({
key={row.id}
className={cn(
"hover:bg-blue-50/50 transition-colors",
getRowClassName?.(row.original),
onRowClick && "cursor-pointer"
)}
onClick={() => onRowClick?.(row.original)}
@@ -0,0 +1,260 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { AlertCircle, Clock, Paperclip, X } from "lucide-react";
import { Modal } from "@/components/ui/dialog";
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 { attachmentsApi } from "@/api/attachments";
import { fetchUsersLookup } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
const complaintSchema = z.object({
description: z.string().trim().min(1, "Problem description is required"),
breakdown_details: z.string().optional(),
priority: z.enum(["critical", "non_critical"]),
notes: z.string().optional(),
received_by_id: z.string().optional(),
});
type ComplaintFormValues = z.infer<typeof complaintSchema>;
interface RaiseComplaintModalProps {
open: boolean;
onClose: () => void;
}
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) {
const navigate = useNavigate();
const qc = useQueryClient();
const user = useAuthStore((s) => s.user);
const isDeptUser = user?.role === "department_user";
const [selectedAsset, setSelectedAsset] = useState<AssetLookupItem | null>(null);
const [files, setFiles] = useState<File[]>([]);
const [serverError, setServerError] = useState<string | null>(null);
const usersQuery = useQuery({
queryKey: ["users-lookup"],
queryFn: fetchUsersLookup,
enabled: open,
});
const {
register,
handleSubmit,
reset,
formState: { errors, isSubmitting },
} = useForm<ComplaintFormValues>({
resolver: zodResolver(complaintSchema),
defaultValues: {
description: "",
breakdown_details: "",
priority: "non_critical",
notes: "",
received_by_id: user?.id ? String(user.id) : "",
},
});
useEffect(() => {
if (!open) return;
setSelectedAsset(null);
setFiles([]);
setServerError(null);
reset({
description: "",
breakdown_details: "",
priority: "non_critical",
notes: "",
received_by_id: user?.id ? String(user.id) : "",
});
}, [open, user?.id, reset]);
function handleFilePick(e: React.ChangeEvent<HTMLInputElement>) {
const picked = Array.from(e.target.files ?? []);
e.target.value = "";
for (const f of picked) {
const err = validateAttachmentFile(f);
if (err) {
setServerError(`${f.name}: ${err}`);
return;
}
}
setServerError(null);
setFiles((prev) => [...prev, ...picked]);
}
async function onSubmit(values: ComplaintFormValues) {
if (!selectedAsset) {
setServerError("Please select an asset first.");
return;
}
setServerError(null);
try {
const created = await complaintsApi.create({
asset_id: selectedAsset.id,
description: values.description.trim(),
breakdown_details: values.breakdown_details?.trim() || null,
priority: values.priority as AssetCriticality,
notes: values.notes?.trim() || null,
received_by_id: values.received_by_id ? Number(values.received_by_id) : null,
});
for (const file of files) {
await attachmentsApi.upload("complaint", created.id, file);
}
await qc.invalidateQueries({ queryKey: ["complaints"] });
await qc.invalidateQueries({ queryKey: ["assets"] });
onClose();
navigate(`/complaints/${created.id}`);
} catch (err) {
setServerError(err instanceof ApiError ? err.detail : "Failed to register complaint.");
}
}
const users = usersQuery.data?.items ?? [];
return (
<Modal
open={open}
onOpenChange={(o) => !o && onClose()}
title="Raise Breakdown / Complaint"
className="max-w-2xl"
>
{serverError && (
<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>{serverError}</span>
</div>
)}
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
<div>
<label className={labelCls}>Select Asset *</label>
<AssetPicker
selectedAsset={selectedAsset}
onSelect={setSelectedAsset}
departmentId={isDeptUser ? user?.department_id ?? undefined : undefined}
/>
</div>
<div className="flex items-center gap-2 rounded-md bg-gray-50 border border-gray-200 px-3 py-2 text-xs text-gray-600">
<Clock className="h-4 w-4 text-gray-400 shrink-0" />
<span>Registered At: Auto-captured by server on submit</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className={labelCls}>Priority *</label>
<select {...register("priority")} className={inputCls}>
<option value="non_critical">Non-Critical</option>
<option value="critical">Critical (Emergency / Life Support)</option>
</select>
</div>
<div>
<label className={labelCls}>Received By</label>
<select {...register("received_by_id")} className={inputCls}>
<option value="">Current User</option>
{users.map((u) => (
<option key={u.id} value={String(u.id)}>
{u.name}
</option>
))}
</select>
</div>
</div>
<div>
<label className={labelCls}>Complaint Description *</label>
<textarea
{...register("description")}
rows={2}
placeholder="Brief summary of the breakdown or issue..."
className={inputCls}
/>
{errors.description && (
<p className="text-xs text-red-600 mt-1">{errors.description.message}</p>
)}
</div>
<div>
<label className={labelCls}>Breakdown Details</label>
<textarea
{...register("breakdown_details")}
rows={2}
placeholder="Error codes, observed symptoms, clinical impact..."
className={inputCls}
/>
</div>
<div>
<label className={labelCls}>Additional Notes</label>
<input
{...register("notes")}
placeholder="Optional caller contact or bay number..."
className={inputCls}
/>
</div>
{/* Multi-file photo/PDF picker */}
<div>
<label className={labelCls}>Photos / Supporting Documents (Optional)</label>
<label className="inline-flex items-center gap-2 px-3 py-2 rounded-md border border-gray-300 bg-white hover:bg-gray-50 text-xs font-medium text-gray-700 cursor-pointer">
<Paperclip className="h-3.5 w-3.5" />
Attach JPG, PNG, or PDF (max 10 MB each)
<input
type="file"
multiple
accept=".jpg,.jpeg,.png,.pdf"
onChange={handleFilePick}
className="hidden"
/>
</label>
{files.length > 0 && (
<ul className="mt-2 space-y-1">
{files.map((f, idx) => (
<li
key={`${f.name}-${idx}`}
className="flex items-center justify-between text-xs bg-gray-50 border border-gray-200 rounded px-2.5 py-1.5"
>
<span className="truncate">{f.name}</span>
<button
type="button"
onClick={() => setFiles((prev) => prev.filter((_, i) => i !== idx))}
className="text-gray-400 hover:text-red-600 ml-2"
>
<X className="h-3.5 w-3.5" />
</button>
</li>
))}
</ul>
)}
</div>
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" loading={isSubmitting}>
Submit Complaint
</Button>
</div>
</form>
</Modal>
);
}
+46
View File
@@ -2,6 +2,7 @@ import {
CheckCircle2,
Wrench,
AlertTriangle,
AlertCircle,
Ban,
Clock,
ShieldAlert,
@@ -199,3 +200,48 @@ export function CriticalityBadge({
</span>
);
}
export function CallStatusBadge({
status,
className,
}: {
status: "open" | "in_progress" | "closed" | string;
className?: string;
}) {
const map: Record<string, { label: string; cls: string; icon: React.ReactNode }> = {
open: {
label: "Open",
cls: "bg-red-100 text-red-800 border border-red-200",
icon: <AlertCircle className="h-3 w-3 shrink-0" />,
},
in_progress: {
label: "In Progress",
cls: "bg-amber-100 text-amber-800 border border-amber-200",
icon: <Clock className="h-3 w-3 shrink-0" />,
},
closed: {
label: "Closed",
cls: "bg-green-100 text-green-800 border border-green-200",
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
},
};
const cfg = map[status] ?? {
label: status,
cls: "bg-gray-100 text-gray-700 border border-gray-200",
icon: <MinusCircle className="h-3 w-3 shrink-0" />,
};
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",
cfg.cls,
className
)}
>
{cfg.icon}
<span>{cfg.label}</span>
</span>
);
}
-1
View File
@@ -89,7 +89,6 @@ const ROLE_CAPABILITIES: Record<Role, ReadonlySet<Capability>> = {
coordinator: new Set<Capability>([
"edit_asset_contracts_only",
"view_assets",
"raise_complaint",
"handle_complaint",
"view_pm",
"manage_calibration_contracts",
File diff suppressed because it is too large Load Diff
+331
View File
@@ -0,0 +1,331 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import { Plus, Search } from "lucide-react";
import {
complaintsApi,
type ComplaintItem,
type CallStatus,
} from "@/api/complaints";
import type { AssetCriticality } from "@/api/assets";
import { departmentsApi, fetchUsersLookup } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
import { can } from "@/lib/permissions";
import { formatDateTime, formatDuration } from "@/lib/format";
import { DataTable } from "@/components/DataTable";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { CallStatusBadge, CriticalityBadge } from "@/components/StatusBadge";
import { RaiseComplaintModal } from "@/components/RaiseComplaintModal";
const CALL_STATUS_CHIPS: { value: CallStatus | ""; label: string }[] = [
{ value: "", label: "All Calls" },
{ value: "open", label: "Open" },
{ value: "in_progress", label: "In Progress" },
{ value: "closed", label: "Closed" },
];
export function ComplaintsPage() {
const navigate = useNavigate();
const user = useAuthStore((s) => s.user);
const role = user?.role;
const isDeptUser = role === "department_user";
const canRaise = can(role, "raise_complaint");
const [q, setQ] = useState("");
const [departmentId, setDepartmentId] = useState<string>("");
const [callStatus, setCallStatus] = useState<CallStatus | "">("");
const [priority, setPriority] = useState<AssetCriticality | "">("");
const [assignedToId, setAssignedToId] = useState<string>("");
const [closureState, setClosureState] = useState<"open_only" | "closed_only" | "">("");
const [dateFrom, setDateFrom] = useState("");
const [dateTo, setDateTo] = useState("");
const [raiseOpen, setRaiseOpen] = useState(false);
const deptsQuery = useQuery({
queryKey: ["departments", "active-only"],
queryFn: () => departmentsApi.list(false),
enabled: !isDeptUser,
});
const usersQuery = useQuery({
queryKey: ["users-lookup"],
queryFn: fetchUsersLookup,
});
const complaintsQuery = useQuery({
queryKey: [
"complaints",
q,
departmentId,
callStatus,
priority,
assignedToId,
closureState,
dateFrom,
dateTo,
],
queryFn: () =>
complaintsApi.list({
q: q.trim() || undefined,
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
call_status: callStatus || undefined,
priority: priority || undefined,
assigned_to_id: assignedToId ? Number(assignedToId) : undefined,
closure_state: closureState || undefined,
date_from: dateFrom || undefined,
date_to: dateTo || undefined,
page_size: 200,
}),
});
const columns: ColumnDef<ComplaintItem, unknown>[] = [
{
accessorKey: "complaint_no",
header: "Complaint No",
enableColumnFilter: true,
cell: ({ getValue }) => (
<span className="font-mono font-semibold text-[#1e3a8a] whitespace-nowrap">
{String(getValue())}
</span>
),
},
{
id: "asset_display",
accessorFn: (row) => `${row.asset_code} ${row.asset_name}`,
header: "Asset",
enableColumnFilter: true,
cell: ({ row }) => (
<div className="min-w-36">
<div className="font-mono text-xs text-[#1e3a8a] font-medium">
{row.original.asset_code}
</div>
<div className="text-xs text-gray-800 truncate">{row.original.asset_name}</div>
</div>
),
},
{
accessorKey: "department_name",
header: "Department",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "—",
},
{
accessorKey: "priority",
header: "Priority",
enableColumnFilter: true,
cell: ({ getValue }) => <CriticalityBadge criticality={String(getValue())} />,
},
{
accessorKey: "call_status",
header: "Call Status",
enableColumnFilter: true,
cell: ({ getValue }) => <CallStatusBadge status={String(getValue())} />,
},
{
accessorKey: "assigned_to_name",
header: "Assigned To",
enableColumnFilter: true,
cell: ({ getValue }) => (getValue() as string | null) || "Unassigned",
},
{
accessorKey: "registered_at",
header: "Registered At",
enableColumnFilter: false,
cell: ({ getValue }) => (
<span className="whitespace-nowrap text-xs">{formatDateTime(getValue() as string)}</span>
),
},
{
accessorKey: "response_time_minutes",
header: "Response Time",
enableColumnFilter: false,
cell: ({ getValue }) => (
<span className="whitespace-nowrap text-xs font-medium">
{formatDuration(getValue() as number | null)}
</span>
),
},
{
accessorKey: "downtime_minutes",
header: "Downtime",
enableColumnFilter: false,
cell: ({ row }) => (
<div className="flex items-center gap-1.5 whitespace-nowrap">
<span className="text-xs font-semibold text-gray-900">
{formatDuration(row.original.downtime_minutes)}
</span>
{row.original.downtime_is_ongoing && (
<Badge variant="danger" className="text-[10px] px-1.5 py-0">
Ongoing
</Badge>
)}
</div>
),
},
{
accessorKey: "closed_at",
header: "Closed At",
enableColumnFilter: false,
cell: ({ getValue }) => (
<span className="whitespace-nowrap text-xs">
{formatDateTime(getValue() as string | null)}
</span>
),
},
];
const departments = deptsQuery.data?.items ?? [];
const techUsers = (usersQuery.data?.items ?? []).filter(
(u) => u.role === "biomedical" || u.role === "system_admin"
);
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">Breakdown &amp; Complaint Register</h1>
<p className="text-sm text-gray-500 mt-0.5">
{isDeptUser && user?.department_name
? `Complaints for ${user.department_name}`
: "Track breakdown calls, response times, downtime, and technical resolution"}
</p>
</div>
{canRaise && (
<Button onClick={() => setRaiseOpen(true)}>
<Plus className="h-4 w-4 mr-1.5" />
Raise Complaint
</Button>
)}
</div>
{/* Filter Bar */}
<div className="bg-white border border-gray-200 rounded-lg p-3.5 space-y-3">
<div className="flex items-center gap-1.5 flex-wrap">
<span className="text-xs font-medium text-gray-500 mr-1">Call Status:</span>
{CALL_STATUS_CHIPS.map((chip) => (
<button
key={chip.value || "all"}
type="button"
onClick={() => setCallStatus(chip.value)}
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
callStatus === chip.value
? "bg-[#1e3a8a] text-white"
: "bg-gray-50 border border-gray-200 text-gray-700 hover:bg-gray-100"
}`}
>
{chip.label}
</button>
))}
</div>
<div className="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 complaint no, asset, description..."
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</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={priority}
onChange={(e) => setPriority(e.target.value as AssetCriticality | "")}
aria-label="Filter by Priority"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Priorities</option>
<option value="critical">Critical</option>
<option value="non_critical">Non-Critical</option>
</select>
<select
value={assignedToId}
onChange={(e) => setAssignedToId(e.target.value)}
aria-label="Filter by Assigned To"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Assignees</option>
{techUsers.map((u) => (
<option key={u.id} value={String(u.id)}>
{u.name}
</option>
))}
</select>
<select
value={closureState}
onChange={(e) =>
setClosureState(e.target.value as "open_only" | "closed_only" | "")
}
aria-label="Filter by Closure State"
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
>
<option value="">All Closure States</option>
<option value="open_only">Unclosed Only</option>
<option value="closed_only">Closed Only</option>
</select>
<div className="flex items-center gap-1.5 lg:col-span-2">
<input
type="date"
aria-label="From date"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
/>
<span className="text-xs text-gray-400">to</span>
<input
type="date"
aria-label="To date"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
className="flex-1 px-2 py-1 text-xs border border-gray-200 rounded-md"
/>
</div>
</div>
</div>
<DataTable
data={complaintsQuery.data?.items ?? []}
columns={columns}
loading={complaintsQuery.isLoading}
globalFilterPlaceholder="Quick filter loaded table..."
exportFilename="poona-hospital-complaints"
emptyMessage="No complaints match the current filters."
onRowClick={(row) => navigate(`/complaints/${row.id}`)}
getRowClassName={(row) =>
row.call_status === "open"
? "bg-red-50/35"
: row.call_status === "in_progress"
? "bg-amber-50/35"
: ""
}
/>
{canRaise && (
<RaiseComplaintModal open={raiseOpen} onClose={() => setRaiseOpen(false)} />
)}
</div>
);
}
-7
View File
@@ -36,13 +36,6 @@ export const DashboardPage = () => (
</div>
</StubPage>
);
export const ComplaintsPage = () => (
<StubPage
title="Breakdown & Complaint Register"
phase={3}
description="Full complaint lifecycle with response time and downtime tracking."
/>
);
export const PMPage = () => (
<StubPage title="Preventive Maintenance" phase={4} description="PM schedules and calendar view." />
);
+149
View File
@@ -0,0 +1,149 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ComplaintDetailPage } from "@/pages/ComplaintDetailPage";
import { complaintsApi, type ComplaintItem } from "@/api/complaints";
import { attachmentsApi } from "@/api/attachments";
import * as mastersApi from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
const MOCK_COMPLAINT: ComplaintItem = {
id: 42,
complaint_no: "CMP-2026-0042",
asset_id: 1,
asset_code: "PHRC-ICU-0001",
asset_name: "Ventilator",
asset_status: "under_repair",
department_id: 1,
department_name: "ICU",
location_name: "ICU Bay 1",
description: "Oxygen sensor alarm",
breakdown_details: "Sensor failing calibration check",
priority: "critical",
notes: null,
registered_at: "2026-11-11T06:00:00Z",
registered_by_id: 3,
registered_by_name: "ICU Nurse",
received_by_id: 2,
received_by_name: "Bio Eng",
received_at: "2026-11-11T06:00:00Z",
assigned_to_id: 2,
assigned_to_name: "Bio Eng",
assigned_at: "2026-11-11T06:10:00Z",
attended_by_id: 2,
attended_by_name: "Bio Eng",
attended_at: "2026-11-11T06:25:00Z",
restored_at: null,
closed_by_id: null,
closed_by_name: null,
closed_at: null,
call_status: "in_progress",
closure_remarks: null,
action_taken: "Replaced flow sensor",
root_cause: "Sensor drift",
corrective_action: "Calibration scheduled",
lessons_learned: null,
ce_name: null,
ce_attended_at: null,
ce_action_taken: null,
spare_required: true,
spare_details: "O2 cell",
spare_cost_estimate: 4500,
response_time_minutes: 25,
downtime_minutes: 1420,
downtime_is_ongoing: true,
downtime_end_milestone: "restored_at",
response_start_setting: "registered_at",
ce_response_time_minutes: null,
updated_at: "2026-11-11T06:30:00Z",
};
function renderPage() {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<QueryClientProvider client={qc}>
<MemoryRouter initialEntries={["/complaints/42"]}>
<Routes>
<Route path="/complaints/:id" element={<ComplaintDetailPage />} />
</Routes>
</MemoryRouter>
</QueryClientProvider>
);
}
describe("ComplaintDetailPage", () => {
beforeEach(() => {
vi.restoreAllMocks();
vi.spyOn(complaintsApi, "get").mockResolvedValue(MOCK_COMPLAINT);
vi.spyOn(complaintsApi, "events").mockResolvedValue({ items: [], total: 0 });
vi.spyOn(attachmentsApi, "list").mockResolvedValue({ items: [], total: 0 });
vi.spyOn(mastersApi, "fetchUsersLookup").mockResolvedValue({
items: [{ id: 2, name: "Bio Eng", role: "biomedical", department_id: null }],
total: 1,
});
});
it("renders technical section read-only with Lock banner for department_user and displays downtime metrics", async () => {
useAuthStore.setState({
user: {
id: 3,
name: "ICU Nurse",
email: "dept@poona.demo",
role: "department_user",
department_id: 1,
department_name: "ICU",
is_active: true,
},
token: "t",
hydrating: false,
});
renderPage();
await waitFor(() => {
expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument();
});
expect(
screen.getByText(/Restricted: Editable by Biomedical team only/i)
).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /Save Technical Details/i })).not.toBeInTheDocument();
// Downtime formatting (1420 mins = 23h 40m) + total mins + Ongoing + milestone
expect(screen.getByText("23h 40m")).toBeInTheDocument();
expect(screen.getByText("1,420 mins")).toBeInTheDocument();
expect(screen.getByText("Ongoing")).toBeInTheDocument();
expect(screen.getByText(/Downtime ends at: restored_at/i)).toBeInTheDocument();
});
it("renders editable technical section for biomedical role", async () => {
useAuthStore.setState({
user: {
id: 2,
name: "Bio Eng",
email: "bio@poona.demo",
role: "biomedical",
department_id: null,
department_name: null,
is_active: true,
},
token: "t",
hydrating: false,
});
renderPage();
await waitFor(() => {
expect(screen.getByText("CMP-2026-0042")).toBeInTheDocument();
});
expect(
screen.queryByText(/Restricted: Editable by Biomedical team only/i)
).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: /Save Technical Details/i })
).toBeInTheDocument();
expect(screen.getByDisplayValue("Replaced flow sensor")).toBeInTheDocument();
});
});
+1
View File
@@ -49,6 +49,7 @@ describe("permissions.can()", () => {
// coordinator
expect(can("coordinator", "edit_asset_contracts_only")).toBe(true);
expect(can("coordinator", "create_edit_assets")).toBe(false);
expect(can("coordinator", "raise_complaint")).toBe(false);
expect(can("coordinator", "handle_complaint")).toBe(true);
expect(can("coordinator", "manage_calibration_contracts")).toBe(true);
expect(can("coordinator", "manage_demo_equipment")).toBe(true);
+1 -1
View File
@@ -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/client.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.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/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./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/client.ts","./src/api/complaints.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.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/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}