Files

844 lines
28 KiB
Python

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,
compute_sla_status,
)
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, int, int]:
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
response_start = str(get_setting_value(db, "response_start", "registered_at"))
critical_sla = int(get_setting_value(db, "critical_complaint_sla_hours", 4))
non_critical_sla = int(get_setting_value(db, "non_critical_complaint_sla_hours", 24))
return milestone, response_start, critical_sla, non_critical_sla
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,
critical_sla_hours: int = 4,
non_critical_sla_hours: int = 24,
) -> 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)
sla_breached, sla_target_hours = compute_sla_status(
c.priority,
reg_at,
att_at,
rst_at,
critical_sla_hours=critical_sla_hours,
non_critical_sla_hours=non_critical_sla_hours,
now_utc=now_utc,
)
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_team=c.assigned_team,
assigned_at=asg_at,
attended_by_id=c.attended_by_id,
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
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,
sla_target_hours=sla_target_hours,
sla_breached=sla_breached,
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, critical_sla, non_critical_sla = _complaint_settings(db)
now_utc = _effective_now_utc(db)
return _to_complaint_out(
comp,
user_names,
milestone,
response_start,
now_utc,
critical_sla_hours=critical_sla,
non_critical_sla_hours=non_critical_sla,
)
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,
location_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 location_id is not None:
query = query.filter(Asset.location_id == location_id)
if asset_id is not None:
query = query.filter(Complaint.asset_id == asset_id)
if call_status:
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, critical_sla, non_critical_sla = _complaint_settings(db)
now_utc = _effective_now_utc(db)
items = [
_to_complaint_out(
c,
user_names,
milestone,
response_start,
now_utc,
critical_sla_hours=critical_sla,
non_critical_sla_hours=non_critical_sla,
)
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,
assigned_team=payload.assigned_team,
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)
if payload.assigned_to_id is None and not payload.assigned_team:
raise HTTPException(status_code=422, detail="Either assigned_to_id or assigned_team must be provided.")
assignee: Optional[User] = None
target_name = payload.assigned_team or ""
if payload.assigned_to_id is not None:
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
if assignee is None:
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
target_name = assignee.name
if payload.assigned_team:
target_name = f"{assignee.name} ({payload.assigned_team})"
old_name: Optional[str] = None
event_type = "assigned"
if comp.assigned_to_id is not None or comp.assigned_team:
event_type = "reassigned"
if comp.assigned_to_id is not None:
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
if comp.assigned_team:
old_name = f"{old_name} ({comp.assigned_team})" if old_name else comp.assigned_team
now = utc_now()
if assignee:
comp.assigned_to_id = assignee.id
if payload.assigned_team is not None:
comp.assigned_team = payload.assigned_team.strip() or None
comp.assigned_at = now
if comp.call_status == "open":
comp.call_status = "in_progress"
comp.updated_by_id = current_user.id
db.add(
ComplaintEvent(
complaint_id=comp.id,
event_type=event_type,
from_value=old_name,
to_value=target_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": comp.assigned_to_id,
"assigned_team": comp.assigned_team,
"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)
require_remarks = bool(get_setting_value(db, "require_closure_remarks", True))
effective_remarks = (
payload.closure_remarks if payload.closure_remarks is not None else comp.closure_remarks
)
if require_remarks and (effective_remarks is None or not str(effective_remarks).strip()):
# Use CodedHTTPException so 422 responses match {"detail": str, "code": str} across the API
raise CodedHTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Closure remarks are required.",
code="CLOSURE_REMARKS_REQUIRED",
)
now = utc_now()
prev_status = comp.call_status
comp.closed_by_id = current_user.id
comp.closed_at = now
if comp.restored_at is None:
comp.restored_at = comp.closed_at
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.restored_at = 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))