From 905f6735a7d3bf5805b26562aebe4fd51c660234 Mon Sep 17 00:00:00 2001 From: Atharv1705 Date: Thu, 12 Nov 2026 12:54:21 +0530 Subject: [PATCH] phase-3: breakdown and complaint register with calculations and permissions --- README.md | 3 +- backend/app/main.py | 3 +- backend/app/models/complaints.py | 1 + backend/app/routers/__init__.py | 13 +- backend/app/routers/complaints.py | 769 +++++++++++++ backend/app/routers/users.py | 4 +- backend/app/schemas/__init__.py | 14 + backend/app/schemas/complaints.py | 147 +++ backend/app/seed/seed.py | 2 + backend/app/services/calculations.py | 100 +- backend/app/services/numbering.py | 24 + backend/app/services/permissions.py | 1 - backend/app/services/settings_service.py | 46 +- backend/tests/conftest.py | 87 +- backend/tests/test_auth_and_permissions.py | 3 +- backend/tests/test_complaints.py | 332 ++++++ frontend/src/App.tsx | 4 +- frontend/src/api/complaints.ts | 153 +++ frontend/src/api/masters.ts | 17 + .../src/components/DataTable/DataTable.tsx | 3 + .../src/components/RaiseComplaintModal.tsx | 260 +++++ frontend/src/components/StatusBadge.tsx | 46 + frontend/src/lib/permissions.ts | 1 - frontend/src/pages/ComplaintDetailPage.tsx | 1008 +++++++++++++++++ frontend/src/pages/ComplaintsPage.tsx | 331 ++++++ frontend/src/pages/stubs.tsx | 7 - frontend/src/test/complaint-detail.test.tsx | 149 +++ frontend/src/test/permissions.test.ts | 1 + frontend/tsconfig.tsbuildinfo | 2 +- 29 files changed, 3505 insertions(+), 26 deletions(-) create mode 100644 backend/app/routers/complaints.py create mode 100644 backend/app/schemas/complaints.py create mode 100644 backend/app/services/numbering.py create mode 100644 backend/tests/test_complaints.py create mode 100644 frontend/src/api/complaints.ts create mode 100644 frontend/src/components/RaiseComplaintModal.tsx create mode 100644 frontend/src/pages/ComplaintDetailPage.tsx create mode 100644 frontend/src/pages/ComplaintsPage.tsx create mode 100644 frontend/src/test/complaint-detail.test.tsx diff --git a/README.md b/README.md index 12889af..c6ad445 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/backend/app/main.py b/backend/app/main.py index 5986abf..02a4716 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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") diff --git a/backend/app/models/complaints.py b/backend/app/models/complaints.py index 6b28014..e8832c2 100644 --- a/backend/app/models/complaints.py +++ b/backend/app/models/complaints.py @@ -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) diff --git a/backend/app/routers/__init__.py b/backend/app/routers/__init__.py index 2a3b0aa..aa29545 100644 --- a/backend/app/routers/__init__.py +++ b/backend/app/routers/__init__.py @@ -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", +] diff --git a/backend/app/routers/complaints.py b/backend/app/routers/complaints.py new file mode 100644 index 0000000..7b13e6c --- /dev/null +++ b/backend/app/routers/complaints.py @@ -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)) diff --git a/backend/app/routers/users.py b/backend/app/routers/users.py index 5f6c86d..18752d1 100644 --- a/backend/app/routers/users.py +++ b/backend/app/routers/users.py @@ -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) diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py index b9b7f8e..28b9a15 100644 --- a/backend/app/schemas/__init__.py +++ b/backend/app/schemas/__init__.py @@ -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, diff --git a/backend/app/schemas/complaints.py b/backend/app/schemas/complaints.py new file mode 100644 index 0000000..0addc1f --- /dev/null +++ b/backend/app/schemas/complaints.py @@ -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 diff --git a/backend/app/seed/seed.py b/backend/app/seed/seed.py index 2ce8b05..3cb6000 100644 --- a/backend/app/seed/seed.py +++ b/backend/app/seed/seed.py @@ -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) diff --git a/backend/app/services/calculations.py b/backend/app/services/calculations.py index 5659392..fd3a94d 100644 --- a/backend/app/services/calculations.py +++ b/backend/app/services/calculations.py @@ -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) diff --git a/backend/app/services/numbering.py b/backend/app/services/numbering.py new file mode 100644 index 0000000..e741765 --- /dev/null +++ b/backend/app/services/numbering.py @@ -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}" diff --git a/backend/app/services/permissions.py b/backend/app/services/permissions.py index 0c91a2d..1435cac 100644 --- a/backend/app/services/permissions.py +++ b/backend/app/services/permissions.py @@ -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", diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.py index 4a52ad4..d6105bd 100644 --- a/backend/app/services/settings_service.py +++ b/backend/app/services/settings_service.py @@ -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: diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index fbd84c0..7ec5038 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -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() diff --git a/backend/tests/test_auth_and_permissions.py b/backend/tests/test_auth_and_permissions.py index 3aed2e9..a221f19 100644 --- a/backend/tests/test_auth_and_permissions.py +++ b/backend/tests/test_auth_and_permissions.py @@ -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( diff --git a/backend/tests/test_complaints.py b/backend/tests/test_complaints.py new file mode 100644 index 0000000..cef2578 --- /dev/null +++ b/backend/tests/test_complaints.py @@ -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" diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c57507d..cff9cfd 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/frontend/src/api/complaints.ts b/frontend/src/api/complaints.ts new file mode 100644 index 0000000..97eb766 --- /dev/null +++ b/frontend/src/api/complaints.ts @@ -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("/complaints", data), + get: (id: number) => api.get(`/complaints/${id}`), + events: (id: number) => + api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`), + update: (id: number, data: ComplaintUpdatePayload) => + api.patch(`/complaints/${id}`, data), + assign: (id: number, data: { assigned_to_id: number; note?: string }) => + api.post(`/complaints/${id}/assign`, data), + attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) => + api.post(`/complaints/${id}/attend`, data), + restore: (id: number, data: { note?: string } = {}) => + api.post(`/complaints/${id}/restore`, data), + close: (id: number, data: { closure_remarks?: string } = {}) => + api.post(`/complaints/${id}/close`, data), + reopen: (id: number, data: { reason: string }) => + api.post(`/complaints/${id}/reopen`, data), + correctTimestamp: ( + id: number, + data: { field: TimestampField; new_value: string; reason: string } + ) => api.post(`/complaints/${id}/correct-timestamp`, data), +}; diff --git a/frontend/src/api/masters.ts b/frontend/src/api/masters.ts index 0d951f7..5ae7dd3 100644 --- a/frontend/src/api/masters.ts +++ b/frontend/src/api/masters.ts @@ -154,3 +154,20 @@ export const usersApi = { ) => api.patch(`/users/${id}`, data), remove: (id: number) => api.delete(`/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( + "/users/lookup" + ); + if (Array.isArray(res)) { + return { items: res, total: res.length }; + } + return res; +} diff --git a/frontend/src/components/DataTable/DataTable.tsx b/frontend/src/components/DataTable/DataTable.tsx index 99b9474..85258fc 100644 --- a/frontend/src/components/DataTable/DataTable.tsx +++ b/frontend/src/components/DataTable/DataTable.tsx @@ -25,6 +25,7 @@ interface DataTableProps { emptyAction?: React.ReactNode; globalFilterPlaceholder?: string; onRowClick?: (row: TData) => void; + getRowClassName?: (row: TData) => string; exportFilename?: string; } @@ -52,6 +53,7 @@ export function DataTable({ emptyAction, globalFilterPlaceholder = "Search...", onRowClick, + getRowClassName, exportFilename = "export", }: DataTableProps) { const [sorting, setSorting] = useState([]); @@ -203,6 +205,7 @@ export function DataTable({ key={row.id} className={cn( "hover:bg-blue-50/50 transition-colors", + getRowClassName?.(row.original), onRowClick && "cursor-pointer" )} onClick={() => onRowClick?.(row.original)} diff --git a/frontend/src/components/RaiseComplaintModal.tsx b/frontend/src/components/RaiseComplaintModal.tsx new file mode 100644 index 0000000..f7a9537 --- /dev/null +++ b/frontend/src/components/RaiseComplaintModal.tsx @@ -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; + +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(null); + const [files, setFiles] = useState([]); + const [serverError, setServerError] = useState(null); + + const usersQuery = useQuery({ + queryKey: ["users-lookup"], + queryFn: fetchUsersLookup, + enabled: open, + }); + + const { + register, + handleSubmit, + reset, + formState: { errors, isSubmitting }, + } = useForm({ + 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) { + 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 ( + !o && onClose()} + title="Raise Breakdown / Complaint" + className="max-w-2xl" + > + {serverError && ( +
+ + {serverError} +
+ )} + +
+
+ + +
+ +
+ + Registered At: Auto-captured by server on submit +
+ +
+
+ + +
+
+ + +
+
+ +
+ +