phase-3: breakdown and complaint register with calculations and permissions
This commit is contained in:
+2
-1
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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))
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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}"
|
||||
@@ -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",
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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"
|
||||
Reference in New Issue
Block a user