Merge pull request 'feat(dashboard): real technician names + technician performance dashboard (relay #748 v3)' (#16) from fm/denya-wahab-tech-perf-20260909 into main

This commit was merged in pull request #16.
This commit is contained in:
2026-09-10 04:37:07 +00:00
10 changed files with 809 additions and 7 deletions
+15
View File
@@ -89,6 +89,7 @@ number. Covered by `tests/test_whatsapp_demo_number.py`.
| GET | `/dashboard/cs` | Client | CS dashboard | | GET | `/dashboard/cs` | Client | CS dashboard |
| GET | `/dashboard/fm` | Client | FM dashboard | | GET | `/dashboard/fm` | Client | FM dashboard |
| GET | `/dashboard/ceo` | Client | CEO dashboard | | GET | `/dashboard/ceo` | Client | CEO dashboard |
| GET | `/dashboard/tech-performance` | Client | Technician performance report (FM + CEO nav) |
| GET | `/tickets` | Client | All Issues filterable table | | GET | `/tickets` | Client | All Issues filterable table |
| GET | `/tickets/new` | Client | Create Issue form | | GET | `/tickets/new` | Client | Create Issue form |
| GET | `/tickets/{id}` | Client | Issue detail with timeline | | GET | `/tickets/{id}` | Client | Issue detail with timeline |
@@ -96,6 +97,20 @@ number. Covered by `tests/test_whatsapp_demo_number.py`.
Frontend: Alpine.js + Tailwind CSS vendored same-origin (no CDN) — see Frontend: Alpine.js + Tailwind CSS vendored same-origin (no CDN) — see
"Frontend assets" below. Auth state in localStorage. Role-based nav routing in `base.html`. "Frontend assets" below. Auth state in localStorage. Role-based nav routing in `base.html`.
### Technician performance (Wahab request)
`GET /api/tickets/tech-performance` (Bearer) aggregates per-technician workload/outcomes by
**real name** using only existing ticket columns (`assigned_to`/`status`/`created_at`/`closed_at`
→ `users.full_name`) — no schema change. Aggregation lives in
`app/services/ticket.py::get_technician_performance`; bucket map `_TECH_STATUS_BUCKETS` defines
`completed` (Completed/Closed), `in_progress`, `escalated`, `cancelled`, and `pending` (remainder),
so the buckets always sum to `total_assigned`. `completion_rate = completed/total_assigned`;
`avg_resolution_hours` averages `created_at → closed_at` only where `closed_at` is set, with
`resolved_without_timestamps` counting finished tasks that lack one. Rows key on user id (same-name
techs stay separate), sorted completed desc → workload → name. UI:
`app/templates/dashboard/tech-performance.html`, linked from FM + CEO nav and the FM
"Technician Workload" card — that card reads `Ticket.assigned_technician_name`, never an id
placeholder. Regression: `tests/test_tech_performance.py`.
### Frontend assets (vendored, LAN-safe) ### Frontend assets (vendored, LAN-safe)
- Alpine.js 3.17.2 + Tailwind Play 3.4.17 are committed under `app/static/vendor/` - Alpine.js 3.17.2 + Tailwind Play 3.4.17 are committed under `app/static/vendor/`
and served at `/static/vendor/…` (mounted in `app/main.py`, versioned and served at `/static/vendor/…` (mounted in `app/main.py`, versioned
+8
View File
@@ -33,6 +33,14 @@ async def ceo_dashboard(request: Request):
return templates.TemplateResponse(request, "dashboard/ceo.html") return templates.TemplateResponse(request, "dashboard/ceo.html")
@router.get("/dashboard/tech-performance", response_class=HTMLResponse)
async def tech_performance_dashboard(request: Request):
"""Technician performance report (FM + CEO). Data comes from
``GET /api/tickets/tech-performance``; the page itself follows the same
client-side auth pattern as the other dashboards."""
return templates.TemplateResponse(request, "dashboard/tech-performance.html")
@router.get("/tickets", response_class=HTMLResponse) @router.get("/tickets", response_class=HTMLResponse)
async def ticket_list(request: Request): async def ticket_list(request: Request):
return templates.TemplateResponse(request, "tickets/list.html") return templates.TemplateResponse(request, "tickets/list.html")
+17
View File
@@ -23,6 +23,7 @@ from app.schemas.ticket import (
CategoryOut, CategoryOut,
CategoryTreeOut, CategoryTreeOut,
SLAStatusOut, SLAStatusOut,
TechnicianPerformanceReportOut,
TicketBrief, TicketBrief,
TicketCreate, TicketCreate,
TicketListResponse, TicketListResponse,
@@ -248,6 +249,22 @@ async def list_tickets(
return TicketListResponse(items=items, total=total, page=page, page_size=effective_page_size) return TicketListResponse(items=items, total=total, page=page, page_size=effective_page_size)
@router.get("/tech-performance", response_model=TechnicianPerformanceReportOut)
async def technician_performance(
db: Annotated[AsyncSession, Depends(get_db)],
_current_user: Annotated[User, Depends(get_current_user)],
) -> dict:
"""Per-technician performance aggregate for the FM/CEO dashboards.
Technician names come from ``users.full_name`` (never ``Tech #<id>``);
counts and resolution times are derived from existing ticket columns, so no
schema change is involved. Registered before ``/{ticket_id}`` so the literal
path is not swallowed by the int-typed ticket-id route. Requires a bearer
token, matching every other endpoint that powers a logged-in dashboard.
"""
return await ticket_service.get_technician_performance(db)
@router.get("/{ticket_id}/transitions") @router.get("/{ticket_id}/transitions")
async def get_ticket_transitions( async def get_ticket_transitions(
ticket_id: int, ticket_id: int,
+54
View File
@@ -129,6 +129,60 @@ class TicketListResponse(BaseModel):
page_size: int page_size: int
# ── Technician performance ───────────────────────────────────────────
class TechnicianPerformanceOut(BaseModel):
"""Per-technician workload and outcome aggregate (by real name).
``open_tickets`` is ``total_assigned - completed - cancelled``;
``pending`` is the remainder bucket (statuses such as New/Logged/Triage/
Assigned plus verification stages) and keeps the named buckets summing to
``total_assigned``. ``avg_resolution_hours`` averages ``created_at ->
closed_at`` and is ``null`` when no finished task carries a timestamp —
``resolved_without_timestamps`` then says how many those are.
"""
technician_id: int
name: str
total_assigned: int
completed: int
closed: int
in_progress: int
escalated: int
cancelled: int
pending: int
open_tickets: int
completion_rate: float
avg_resolution_hours: float | None = None
resolved_with_timestamps: int
resolved_without_timestamps: int
status_breakdown: dict[str, int] = {}
class TechnicianPerformanceTotalsOut(BaseModel):
"""Fleet-wide roll-up of :class:`TechnicianPerformanceOut`."""
technicians: int
total_tickets: int
total_assigned: int
completed: int
closed: int
in_progress: int
escalated: int
cancelled: int
pending: int
open_tickets: int
completion_rate: float
avg_resolution_hours: float | None = None
resolved_with_timestamps: int
resolved_without_timestamps: int
unassigned_tickets: int
class TechnicianPerformanceReportOut(BaseModel):
"""Response for ``GET /api/tickets/tech-performance``."""
generated_at: datetime
technicians: list[TechnicianPerformanceOut]
totals: TechnicianPerformanceTotalsOut
# ── SLA ────────────────────────────────────────────────────────────── # ── SLA ──────────────────────────────────────────────────────────────
class SLAStatusOut(BaseModel): class SLAStatusOut(BaseModel):
priority: str | None = None priority: str | None = None
+163
View File
@@ -345,6 +345,169 @@ async def update_ticket(
return ticket return ticket
# ── Technician performance ───────────────────────────────────────────
# Buckets for the technician-performance dashboard (Wahab request). The map is
# intentionally not exhaustive: any status missing from it is counted as
# "pending" so the named buckets always sum to ``total_assigned`` and no
# assigned ticket is silently dropped from the report.
_TECH_STATUS_BUCKETS: dict[str, str] = {
"Completed": "completed",
"Closed": "completed",
"Accepted": "in_progress",
"Travelling": "in_progress",
"On Site": "in_progress",
"In Progress": "in_progress",
"Waiting Parts": "in_progress",
"Escalated": "escalated",
"Cancelled": "cancelled",
}
def _bucket_for_status(status: str) -> str:
"""Map a ticket status onto its technician-performance bucket."""
return _TECH_STATUS_BUCKETS.get(status, "pending")
def _empty_tech_entry(technician_id: int, name: str) -> dict[str, Any]:
return {
"technician_id": technician_id,
"name": name,
"total_assigned": 0,
"completed": 0,
"closed": 0,
"in_progress": 0,
"escalated": 0,
"cancelled": 0,
"pending": 0,
"open_tickets": 0,
"completion_rate": 0.0,
"avg_resolution_hours": None,
"resolved_with_timestamps": 0,
"resolved_without_timestamps": 0,
"status_breakdown": {},
"_hours_sum": 0.0,
}
async def get_technician_performance(db: AsyncSession) -> dict[str, Any]:
"""Aggregate per-technician workload/outcome stats for the dashboard.
Derived entirely from existing ``tickets`` columns (``assigned_to``,
``status``, ``created_at``, ``closed_at``) joined to ``users.full_name`` —
no schema change. Technician identity is keyed on the user id so two people
sharing a display name stay separate rows, while the reported label is the
real name (never ``"Tech #<id>"``).
Completion rate is ``completed / total_assigned`` (Completed + Closed count
as completed). Resolution time averages ``created_at -> closed_at`` only for
rows where ``closed_at`` is set; the number of finished tasks lacking that
timestamp is reported separately so an absent average is never mistaken for
missing work.
"""
rows = (
await db.execute(
select(
Ticket.assigned_to,
User.full_name,
Ticket.status,
Ticket.created_at,
Ticket.closed_at,
)
.join(User, User.id == Ticket.assigned_to)
.where(Ticket.assigned_to.is_not(None))
)
).all()
unassigned_result = await db.execute(
select(func.count(Ticket.id)).where(Ticket.assigned_to.is_(None))
)
unassigned_tickets = unassigned_result.scalar() or 0
by_tech: dict[int, dict[str, Any]] = {}
for assigned_to, full_name, status, created_at, closed_at in rows:
entry = by_tech.get(assigned_to)
if entry is None:
entry = _empty_tech_entry(assigned_to, full_name)
by_tech[assigned_to] = entry
entry["total_assigned"] += 1
bucket = _bucket_for_status(status)
if bucket == "completed":
entry["completed"] += 1
if status == "Closed":
entry["closed"] += 1
if closed_at is not None and created_at is not None:
hours = (closed_at - created_at).total_seconds() / 3600
entry["_hours_sum"] += hours
entry["resolved_with_timestamps"] += 1
else:
entry["resolved_without_timestamps"] += 1
else:
entry[bucket] += 1
breakdown = entry["status_breakdown"]
breakdown[status] = breakdown.get(status, 0) + 1
technicians: list[dict[str, Any]] = []
total_assigned = total_completed = total_closed = 0
total_in_progress = total_escalated = total_cancelled = total_pending = 0
total_hours = 0.0
total_with_timestamps = total_without_timestamps = 0
for entry in by_tech.values():
assigned = entry["total_assigned"]
entry["open_tickets"] = assigned - entry["completed"] - entry["cancelled"]
entry["completion_rate"] = round(entry["completed"] / assigned * 100, 1) if assigned else 0.0
if entry["resolved_with_timestamps"]:
entry["avg_resolution_hours"] = round(
entry["_hours_sum"] / entry["resolved_with_timestamps"], 1
)
entry["status_breakdown"] = dict(
sorted(entry["status_breakdown"].items(), key=lambda kv: (-kv[1], kv[0]))
)
total_assigned += assigned
total_completed += entry["completed"]
total_closed += entry["closed"]
total_in_progress += entry["in_progress"]
total_escalated += entry["escalated"]
total_cancelled += entry["cancelled"]
total_pending += entry["pending"]
total_hours += entry["_hours_sum"]
total_with_timestamps += entry["resolved_with_timestamps"]
total_without_timestamps += entry["resolved_without_timestamps"]
del entry["_hours_sum"]
technicians.append(entry)
# Busiest/most productive first; ties broken by workload then real name.
technicians.sort(key=lambda e: (-e["completed"], -e["total_assigned"], e["name"].lower()))
totals = {
"technicians": len(technicians),
"total_assigned": total_assigned,
"completed": total_completed,
"closed": total_closed,
"in_progress": total_in_progress,
"escalated": total_escalated,
"cancelled": total_cancelled,
"pending": total_pending,
"open_tickets": total_assigned - total_completed - total_cancelled,
"completion_rate": round(total_completed / total_assigned * 100, 1) if total_assigned else 0.0,
"avg_resolution_hours": round(total_hours / total_with_timestamps, 1) if total_with_timestamps else None,
"resolved_with_timestamps": total_with_timestamps,
"resolved_without_timestamps": total_without_timestamps,
"unassigned_tickets": unassigned_tickets,
"total_tickets": total_assigned + unassigned_tickets,
}
return {
"generated_at": datetime.now(timezone.utc),
"technicians": technicians,
"totals": totals,
}
async def delete_ticket(db: AsyncSession, ticket_id: int) -> Ticket: async def delete_ticket(db: AsyncSession, ticket_id: int) -> Ticket:
"""Delete a ticket and all dependent rows (timeline, photos, escalations). """Delete a ticket and all dependent rows (timeline, photos, escalations).
+12 -1
View File
@@ -89,6 +89,7 @@
<template x-if="isFM"> <template x-if="isFM">
<div class="hidden md:flex space-x-1 ml-6"> <div class="hidden md:flex space-x-1 ml-6">
<a href="/dashboard/fm" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath === '/dashboard/fm' ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Dashboard</a> <a href="/dashboard/fm" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath === '/dashboard/fm' ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Dashboard</a>
<a href="/dashboard/tech-performance" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath === '/dashboard/tech-performance' ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Tech Performance</a>
<a href="/tickets" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath.startsWith('/tickets') && !currentPath.endsWith('/new') ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">All Issues</a> <a href="/tickets" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath.startsWith('/tickets') && !currentPath.endsWith('/new') ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">All Issues</a>
<a href="/tickets/new" class="px-3 py-2 rounded-md text-sm font-medium text-gray-300 hover:text-white hover:bg-denya-800/50 transition-colors">Create Issue</a> <a href="/tickets/new" class="px-3 py-2 rounded-md text-sm font-medium text-gray-300 hover:text-white hover:bg-denya-800/50 transition-colors">Create Issue</a>
</div> </div>
@@ -96,6 +97,7 @@
<template x-if="isExecutive"> <template x-if="isExecutive">
<div class="hidden md:flex space-x-1 ml-6"> <div class="hidden md:flex space-x-1 ml-6">
<a href="/dashboard/ceo" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath === '/dashboard/ceo' ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Dashboard</a> <a href="/dashboard/ceo" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath === '/dashboard/ceo' ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Dashboard</a>
<a href="/dashboard/tech-performance" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath === '/dashboard/tech-performance' ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Tech Performance</a>
<a href="/tickets" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath.startsWith('/tickets') ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Issues</a> <a href="/tickets" class="px-3 py-2 rounded-md text-sm font-medium transition-colors" :class="currentPath.startsWith('/tickets') ? 'bg-denya-800 text-gold' : 'text-gray-300 hover:text-white hover:bg-denya-800/50'">Issues</a>
</div> </div>
</template> </template>
@@ -113,16 +115,25 @@
<!-- Mobile Nav --> <!-- Mobile Nav -->
<div class="md:hidden border-b bg-[#0d2b18] border-denya-800" x-show="isLoggedIn" x-cloak> <div class="md:hidden border-b bg-[#0d2b18] border-denya-800" x-show="isLoggedIn" x-cloak>
<template x-if="isCS || isFM"> <template x-if="isCS">
<div class="flex overflow-x-auto px-4 py-2 space-x-2"> <div class="flex overflow-x-auto px-4 py-2 space-x-2">
<a href="/dashboard/cs" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath === '/dashboard/cs' ? 'bg-denya-800 text-gold' : 'text-gray-300'">Dashboard</a> <a href="/dashboard/cs" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath === '/dashboard/cs' ? 'bg-denya-800 text-gold' : 'text-gray-300'">Dashboard</a>
<a href="/tickets" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath.startsWith('/tickets') && !currentPath.endsWith('/new') ? 'bg-denya-800 text-gold' : 'text-gray-300'">Issues</a> <a href="/tickets" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath.startsWith('/tickets') && !currentPath.endsWith('/new') ? 'bg-denya-800 text-gold' : 'text-gray-300'">Issues</a>
<a href="/tickets/new" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap text-gray-300">New Issue</a> <a href="/tickets/new" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap text-gray-300">New Issue</a>
</div> </div>
</template> </template>
<template x-if="isFM">
<div class="flex overflow-x-auto px-4 py-2 space-x-2">
<a href="/dashboard/fm" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath === '/dashboard/fm' ? 'bg-denya-800 text-gold' : 'text-gray-300'">Dashboard</a>
<a href="/dashboard/tech-performance" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath === '/dashboard/tech-performance' ? 'bg-denya-800 text-gold' : 'text-gray-300'">Tech Performance</a>
<a href="/tickets" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath.startsWith('/tickets') && !currentPath.endsWith('/new') ? 'bg-denya-800 text-gold' : 'text-gray-300'">Issues</a>
<a href="/tickets/new" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap text-gray-300">New Issue</a>
</div>
</template>
<template x-if="isExecutive"> <template x-if="isExecutive">
<div class="flex overflow-x-auto px-4 py-2 space-x-2"> <div class="flex overflow-x-auto px-4 py-2 space-x-2">
<a href="/dashboard/ceo" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath === '/dashboard/ceo' ? 'bg-denya-800 text-gold' : 'text-gray-300'">CEO Dashboard</a> <a href="/dashboard/ceo" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath === '/dashboard/ceo' ? 'bg-denya-800 text-gold' : 'text-gray-300'">CEO Dashboard</a>
<a href="/dashboard/tech-performance" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap" :class="currentPath === '/dashboard/tech-performance' ? 'bg-denya-800 text-gold' : 'text-gray-300'">Tech Performance</a>
<a href="/tickets" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap text-gray-300">Issues</a> <a href="/tickets" class="px-3 py-1.5 rounded text-sm font-medium whitespace-nowrap text-gray-300">Issues</a>
</div> </div>
</template> </template>
+6 -3
View File
@@ -1,9 +1,12 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<div x-data="ceoDashboard()" x-init="init()"> <div x-data="ceoDashboard()" x-init="init()">
<div class="mb-6"> <div class="mb-6 flex flex-wrap items-start justify-between gap-3">
<h1 class="text-2xl font-bold text-gray-900">Executive Dashboard</h1> <div>
<p class="text-gray-500 mt-1">Read-only strategic overview</p> <h1 class="text-2xl font-bold text-gray-900">Executive Dashboard</h1>
<p class="text-gray-500 mt-1">Read-only strategic overview</p>
</div>
<a href="/dashboard/tech-performance" class="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-700">Technician Performance →</a>
</div> </div>
<!-- Executive KPI Cards --> <!-- Executive KPI Cards -->
+8 -3
View File
@@ -80,7 +80,10 @@
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8"> <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
<!-- Tech Workload --> <!-- Tech Workload -->
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5"> <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
<h3 class="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Technician Workload</h3> <div class="flex items-center justify-between mb-4">
<h3 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">Technician Workload</h3>
<a href="/dashboard/tech-performance" class="text-xs text-denya-600 hover:text-denya-800">Performance →</a>
</div>
<div class="space-y-3"> <div class="space-y-3">
<template x-for="tech in techWorkload" :key="tech.id"> <template x-for="tech in techWorkload" :key="tech.id">
<div class="flex items-center justify-between p-2 hover:bg-gray-50 rounded"> <div class="flex items-center justify-between p-2 hover:bg-gray-50 rounded">
@@ -251,11 +254,13 @@
this.kpi.westJobs = active.filter(t => t.unit_id && unitMap[t.unit_id] === 'West').length; this.kpi.westJobs = active.filter(t => t.unit_id && unitMap[t.unit_id] === 'West').length;
} catch (e) { console.error('Property stats error', e); } } catch (e) { console.error('Property stats error', e); }
// Tech workload (simulated from assigned_to counts) // Tech workload — real technician names (Ticket.assigned_technician_name),
// never an id placeholder; keyed on user id so two people sharing a
// display name stay separate rows.
const techMap = {}; const techMap = {};
active.forEach(t => { active.forEach(t => {
if (t.assigned_to) { if (t.assigned_to) {
if (!techMap[t.assigned_to]) techMap[t.assigned_to] = { id: t.assigned_to, name: `Tech #${t.assigned_to}`, activeJobs: 0 }; if (!techMap[t.assigned_to]) techMap[t.assigned_to] = { id: t.assigned_to, name: t.assigned_technician_name || 'Unassigned', activeJobs: 0 };
techMap[t.assigned_to].activeJobs++; techMap[t.assigned_to].activeJobs++;
} }
}); });
@@ -0,0 +1,239 @@
{% extends "base.html" %}
{% block content %}
<div x-data="techPerformance()" x-init="init()">
<div class="mb-6 flex flex-wrap items-start justify-between gap-3">
<div>
<h1 class="text-2xl font-bold text-gray-900">Technician Performance</h1>
<p class="text-gray-500 mt-1">Tasks completed per technician, by name — FM &amp; CEO view</p>
</div>
<div class="flex items-center space-x-2">
<a x-show="isFM" href="/dashboard/fm" class="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-700">FM Dashboard</a>
<a x-show="isExecutive" href="/dashboard/ceo" class="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-700">CEO Dashboard</a>
<button @click="loadData()" class="px-3 py-2 text-sm bg-denya-700 text-white rounded-lg hover:bg-denya-800">Refresh</button>
</div>
</div>
<!-- KPI Cards -->
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Technicians</p>
<p class="text-3xl font-bold text-gray-900 mt-1" x-text="totals.technicians || 0"></p>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Assigned</p>
<p class="text-3xl font-bold text-gray-900 mt-1" x-text="totals.total_assigned || 0"></p>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Completed</p>
<p class="text-3xl font-bold text-green-600 mt-1" x-text="totals.completed || 0"></p>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Completion Rate</p>
<p class="text-3xl font-bold mt-1" :class="rateClass(totals.completion_rate)" x-text="formatRate(totals.completion_rate)"></p>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Avg Resolution</p>
<p class="text-3xl font-bold text-gray-900 mt-1" x-text="formatHours(totals.avg_resolution_hours)"></p>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
<p class="text-xs text-gray-500 font-medium uppercase tracking-wide">Open Tasks</p>
<p class="text-3xl font-bold text-orange-600 mt-1" x-text="totals.open_tickets || 0"></p>
</div>
</div>
<!-- Status strip -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
<span class="text-sm font-medium text-sky-700">In Progress</span>
<span class="text-2xl font-bold text-sky-700" x-text="totals.in_progress || 0"></span>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
<span class="text-sm font-medium text-red-700">Escalated</span>
<span class="text-2xl font-bold text-red-700" x-text="totals.escalated || 0"></span>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
<span class="text-sm font-medium text-gray-600">Pending / In review</span>
<span class="text-2xl font-bold text-gray-700" x-text="totals.pending || 0"></span>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between">
<span class="text-sm font-medium text-gray-500">Cancelled</span>
<span class="text-2xl font-bold text-gray-500" x-text="totals.cancelled || 0"></span>
</div>
</div>
<!-- Error state -->
<div x-show="error" class="mb-6 p-4 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700">
<span class="font-semibold">Could not load technician performance.</span>
<span x-text="error"></span>
</div>
<!-- Per-technician table -->
<div class="bg-white rounded-xl shadow-sm border border-gray-200">
<div class="px-5 py-4 border-b border-gray-200 flex flex-wrap items-center justify-between gap-3">
<h3 class="text-sm font-semibold text-gray-700 uppercase tracking-wide">By Technician</h3>
<div class="flex items-center space-x-2 text-sm">
<label for="tech-sort" class="text-gray-500">Sort by</label>
<select id="tech-sort" x-model="sortKey" class="border border-gray-300 rounded-lg px-2 py-1.5 text-sm text-gray-700 bg-white">
<option value="completed">Completed</option>
<option value="total_assigned">Workload (assigned)</option>
<option value="completion_rate">Completion rate</option>
<option value="avg_resolution_hours">Avg resolution</option>
<option value="name">Name</option>
</select>
<button @click="dir = dir === 'desc' ? 'asc' : 'desc'" class="px-2 py-1.5 text-xs border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-600" x-text="dir === 'desc' ? 'Desc ↓' : 'Asc ↑'"></button>
</div>
</div>
<div class="overflow-x-auto" x-show="technicians.length">
<table class="w-full text-sm">
<thead class="bg-gray-50 text-gray-600 text-xs uppercase tracking-wider">
<tr>
<th class="px-5 py-3 text-left">Technician</th>
<th class="px-4 py-3 text-right">Assigned</th>
<th class="px-4 py-3 text-right">Completed</th>
<th class="px-4 py-3 text-right">In Progress</th>
<th class="px-4 py-3 text-right">Escalated</th>
<th class="px-4 py-3 text-right">Pending</th>
<th class="px-4 py-3 text-right">Cancelled</th>
<th class="px-5 py-3 text-left min-w-[160px]">Completion Rate</th>
<th class="px-4 py-3 text-right">Avg Resolution</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<template x-for="tech in sortedTechnicians" :key="tech.technician_id">
<tr class="hover:bg-gray-50 transition" :title="breakdownTitle(tech)">
<td class="px-5 py-3">
<div class="flex items-center space-x-3">
<div class="w-8 h-8 bg-denya-100 rounded-full flex items-center justify-center text-sm font-medium text-denya-700" x-text="initial(tech.name)"></div>
<span class="font-medium text-gray-800" x-text="tech.name"></span>
</div>
</td>
<td class="px-4 py-3 text-right font-medium text-gray-700" x-text="tech.total_assigned"></td>
<td class="px-4 py-3 text-right font-semibold text-green-700" x-text="tech.completed"></td>
<td class="px-4 py-3 text-right text-sky-700" x-text="tech.in_progress"></td>
<td class="px-4 py-3 text-right" :class="tech.escalated ? 'text-red-600 font-medium' : 'text-gray-400'" x-text="tech.escalated"></td>
<td class="px-4 py-3 text-right text-gray-600" x-text="tech.pending"></td>
<td class="px-4 py-3 text-right" :class="tech.cancelled ? 'text-gray-500' : 'text-gray-300'" x-text="tech.cancelled"></td>
<td class="px-5 py-3">
<div class="flex items-center space-x-2">
<div class="flex-1 bg-gray-100 rounded-full h-2.5 overflow-hidden">
<div class="h-full rounded-full transition-all" :class="barClass(tech.completion_rate)" :style="'width: ' + Math.min(tech.completion_rate, 100) + '%'"></div>
</div>
<span class="text-xs font-medium text-gray-600 w-12 text-right" x-text="formatRate(tech.completion_rate)"></span>
</div>
</td>
<td class="px-4 py-3 text-right text-gray-700">
<span x-text="formatHours(tech.avg_resolution_hours)"></span>
<span x-show="tech.resolved_without_timestamps > 0" class="block text-[11px] text-gray-400"
x-text="tech.resolved_without_timestamps + ' task' + (tech.resolved_without_timestamps === 1 ? '' : 's') + ' without timestamps'"></span>
</td>
</tr>
</template>
</tbody>
</table>
</div>
<!-- Empty state -->
<div x-show="!technicians.length && !error" class="px-5 py-16 text-center">
<p class="text-gray-500 font-medium">No technician assignments yet</p>
<p class="text-gray-400 text-sm mt-1">Once tickets are assigned to a technician they will appear here with their completion rate and resolution time.</p>
</div>
<div x-show="technicians.length" class="px-5 py-3 border-t border-gray-100 text-xs text-gray-400 flex flex-wrap items-center justify-between gap-2">
<span>Completion rate = completed (Completed + Closed) ÷ assigned. Avg resolution spans created → closed where the close timestamp exists.</span>
<span><span x-text="totals.unassigned_tickets || 0"></span> ticket(s) have no technician assigned and are excluded from the rows above.</span>
</div>
</div>
</div>
<script>
function techPerformance() {
return {
technicians: [],
totals: {},
sortKey: 'completed',
dir: 'desc',
error: '',
get isFM() { return app().isFM },
get isExecutive() { return app().isExecutive },
get sortedTechnicians() {
const list = [...this.technicians];
const key = this.sortKey;
const flip = this.dir === 'asc' ? 1 : -1;
list.sort((a, b) => {
if (key === 'name') {
return flip * a.name.localeCompare(b.name);
}
let av = a[key];
let bv = b[key];
// Missing resolution times sort last in either direction;
// two missing values fall through to the name tiebreak.
if (key === 'avg_resolution_hours') {
const aMissing = av === null || av === undefined;
const bMissing = bv === null || bv === undefined;
if (aMissing || bMissing) {
if (aMissing && bMissing) return a.name.localeCompare(b.name);
return aMissing ? 1 : -1;
}
}
av = av || 0;
bv = bv || 0;
if (av === bv) return a.name.localeCompare(b.name);
return flip * (av - bv);
});
return list;
},
async init() {
await this.loadData();
},
async loadData() {
this.error = '';
try {
const data = await app().apiGet('/api/tickets/tech-performance');
this.technicians = data?.technicians || [];
this.totals = data?.totals || {};
} catch (e) {
this.error = e.message || 'Unknown error';
}
},
formatRate(rate) {
if (rate === null || rate === undefined) return '—';
return `${rate}%`;
},
formatHours(hours) {
if (hours === null || hours === undefined) return '—';
if (hours < 1) return `${Math.round(hours * 60)}m`;
return `${hours}h`;
},
initial(name) {
return (name || '?').charAt(0).toUpperCase();
},
rateClass(rate) {
if (!rate) return 'text-gray-400';
if (rate >= 70) return 'text-green-600';
if (rate >= 40) return 'text-yellow-600';
return 'text-red-600';
},
barClass(rate) {
if (rate >= 70) return 'bg-green-500';
if (rate >= 40) return 'bg-yellow-500';
return 'bg-red-500';
},
breakdownTitle(tech) {
const parts = Object.entries(tech.status_breakdown || {}).map(([s, n]) => `${s}: ${n}`);
return parts.length ? parts.join(' · ') : '';
}
}
}
</script>
{% endblock %}
+287
View File
@@ -0,0 +1,287 @@
"""Tests for the technician-performance dashboard and the ``Tech #N`` fix.
Anchors two Wahab-facing defects/requests:
1. The FM dashboard built its "Technician Workload" card from
``Tech #<user id>`` instead of the technician's real name. The data sources
the card consumes must expose the technician's real name via
``assigned_technician_name``, never an id placeholder.
2. ``GET /api/tickets/tech-performance`` reports per-technician workload and
outcomes by real name: totals, per-status buckets, completion rate and
``created_at -> closed_at`` resolution times. Everything derives from
existing ticket columns — no schema change.
"""
from __future__ import annotations
from datetime import datetime
import pytest
from sqlalchemy import select
from app.core.database import async_session_factory
from app.models.ticket import Ticket
from app.models.user import User
pytestmark = pytest.mark.asyncio
async def _login(client, email: str = "wahab@denya.com", password: str = "denya123") -> str:
resp = await client.post("/api/auth/login", json={"email": email, "password": password})
assert resp.status_code == 200, resp.text
return resp.json()["access_token"]
def _auth(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
async def _user_id(email: str) -> int:
async with async_session_factory() as session:
user = (
await session.execute(select(User).where(User.email == email))
).scalar_one()
return user.id
async def _seed_tickets(specs: list[dict]) -> None:
"""Insert tickets directly so tests control status/timestamps exactly."""
async with async_session_factory() as session:
for i, spec in enumerate(specs):
session.add(Ticket(ticket_number=f"PAV-PERF-{i:05d}", **spec))
await session.commit()
async def _make_user(email: str, full_name: str, role: str = "Tech") -> int:
"""Create a user directly (no API) so tests can build same-name technicians."""
async with async_session_factory() as session:
user = User(email=email, password_hash="not-a-real-hash", full_name=full_name, role=role)
session.add(user)
await session.commit()
await session.refresh(user)
return user.id
def _ticket(status: str, assigned_to: int | None, *, created_at: datetime | None = None,
closed_at: datetime | None = None) -> dict:
spec: dict = {
"status": status,
"priority": "medium",
"description": f"{status} ticket",
"assigned_to": assigned_to,
}
if created_at is not None:
spec["created_at"] = created_at
if closed_at is not None:
spec["closed_at"] = closed_at
return spec
# ── 3a. Real technician names on the workload data paths ─────────────
async def test_workload_sources_report_real_technician_names(client):
"""The FM workload card reads ``/api/tickets?page_size=200`` and the
performance report reads ``/api/tickets/tech-performance``. For an assigned
ticket both must expose the technician's real full name, never a
``Tech #<id>`` placeholder.
"""
prosper = await _user_id("prosper@denya.com")
await _seed_tickets([_ticket("In Progress", prosper), _ticket("Escalated", prosper)])
token = await _login(client)
list_resp = await client.get("/api/tickets?page_size=200", headers=_auth(token))
assert list_resp.status_code == 200
active = [
t for t in list_resp.json()["items"]
if t["status"] not in ("Closed", "Completed", "Cancelled")
]
# Same mapping the FM workload card builds from active assigned tickets.
workload: dict[int, str] = {}
for t in active:
if t["assigned_to"]:
workload.setdefault(t["assigned_to"], t["assigned_technician_name"] or "Unassigned")
assert workload == {prosper: "Prosper"}
perf_resp = await client.get("/api/tickets/tech-performance", headers=_auth(token))
assert perf_resp.status_code == 200
rows = {t["technician_id"]: t for t in perf_resp.json()["technicians"]}
assert rows[prosper]["name"] == "Prosper"
assert all(not row["name"].startswith("Tech #") for row in rows.values())
# ── Page + route wiring ──────────────────────────────────────────────
async def test_tech_performance_page_is_same_origin(client):
"""The new dashboard is reachable and uses only same-origin assets."""
resp = await client.get("/dashboard/tech-performance")
assert resp.status_code == 200
body = resp.text
assert "/api/tickets/tech-performance" in body
assert "https://" not in body
assert "cdn." not in body
async def test_base_nav_links_fm_and_ceo_to_tech_performance(client):
"""FM and CEO navigation exposes the report."""
for path in ("/dashboard/fm", "/dashboard/ceo"):
body = (await client.get(path)).text
assert "/dashboard/tech-performance" in body
async def test_tech_performance_requires_auth(client):
"""The aggregate endpoint is bearer-gated, like other dashboard data paths."""
resp = await client.get("/api/tickets/tech-performance")
assert resp.status_code == 401
async def test_tech_performance_route_not_shadowed_by_ticket_id(client):
"""`/tech-performance` is a literal route, not an int ticket id (no 422)."""
token = await _login(client)
resp = await client.get("/api/tickets/tech-performance", headers=_auth(token))
assert resp.status_code == 200
# ── 3b. Aggregation ──────────────────────────────────────────────────
async def test_tech_performance_empty_state(client):
"""No assigned tickets → empty rows and a fully zeroed roll-up."""
token = await _login(client)
resp = await client.get("/api/tickets/tech-performance", headers=_auth(token))
assert resp.status_code == 200
data = resp.json()
assert data["technicians"] == []
assert data["totals"]["technicians"] == 0
assert data["totals"]["total_assigned"] == 0
assert data["totals"]["completion_rate"] == 0.0
assert data["totals"]["avg_resolution_hours"] is None
async def test_tech_performance_aggregates_by_real_name(client):
"""Counts, completion rate, aging, sorting and totals per technician."""
prosper = await _user_id("prosper@denya.com")
sam = await _user_id("sam@denya.com")
await _seed_tickets(
[
# Prosper: 2 completed (one timestamped), 1 escalated, 1 in progress, 1 cancelled
_ticket("Completed", prosper, created_at=datetime(2026, 1, 1, 0, 0),
closed_at=datetime(2026, 1, 1, 10, 0)),
_ticket("Completed", prosper),
_ticket("Escalated", prosper),
_ticket("In Progress", prosper),
_ticket("Cancelled", prosper),
# Sam: 3 closed (timestamped), 1 assigned, 1 awaiting verification
_ticket("Closed", sam, created_at=datetime(2026, 1, 1, 0, 0),
closed_at=datetime(2026, 1, 2, 0, 0)),
_ticket("Closed", sam, created_at=datetime(2026, 1, 1, 0, 0),
closed_at=datetime(2026, 1, 3, 0, 0)),
_ticket("Closed", sam, created_at=datetime(2026, 1, 1, 0, 0),
closed_at=datetime(2026, 1, 4, 0, 0)),
_ticket("Assigned", sam),
_ticket("On-Field Verification", sam),
# Unassigned tickets are reported separately, never as a fake technician.
_ticket("Logged", None),
_ticket("New", None),
]
)
token = await _login(client)
resp = await client.get("/api/tickets/tech-performance", headers=_auth(token))
assert resp.status_code == 200
data = resp.json()
by_name = {t["name"]: t for t in data["technicians"]}
assert set(by_name) == {"Prosper", "Sam"}
assert all("Tech #" not in name for name in by_name)
prosper_row = by_name["Prosper"]
assert prosper_row["technician_id"] == prosper
assert prosper_row["total_assigned"] == 5
assert prosper_row["completed"] == 2
assert prosper_row["closed"] == 0
assert prosper_row["in_progress"] == 1
assert prosper_row["escalated"] == 1
assert prosper_row["cancelled"] == 1
assert prosper_row["pending"] == 0
# Buckets always reconcile with the assigned total.
assert (
prosper_row["completed"] + prosper_row["in_progress"] + prosper_row["escalated"]
+ prosper_row["cancelled"] + prosper_row["pending"]
) == prosper_row["total_assigned"]
assert prosper_row["open_tickets"] == 2
assert prosper_row["completion_rate"] == 40.0
assert prosper_row["avg_resolution_hours"] == 10.0
assert prosper_row["resolved_with_timestamps"] == 1
assert prosper_row["resolved_without_timestamps"] == 1
assert prosper_row["status_breakdown"] == {"Completed": 2, "Cancelled": 1, "Escalated": 1, "In Progress": 1}
sam_row = by_name["Sam"]
assert sam_row["total_assigned"] == 5
assert sam_row["completed"] == 3
assert sam_row["closed"] == 3
assert sam_row["in_progress"] == 0
assert sam_row["pending"] == 2
assert sam_row["open_tickets"] == 2
assert sam_row["completion_rate"] == 60.0
assert sam_row["avg_resolution_hours"] == 48.0
assert sam_row["resolved_without_timestamps"] == 0
assert sam_row["status_breakdown"] == {"Closed": 3, "Assigned": 1, "On-Field Verification": 1}
# Sorted by completed desc → Sam first.
assert [t["name"] for t in data["technicians"]] == ["Sam", "Prosper"]
totals = data["totals"]
assert totals["technicians"] == 2
assert totals["total_assigned"] == 10
assert totals["completed"] == 5
assert totals["closed"] == 3
assert totals["in_progress"] == 1
assert totals["escalated"] == 1
assert totals["cancelled"] == 1
assert totals["pending"] == 2
assert totals["open_tickets"] == 4
assert totals["completion_rate"] == 50.0
# Fleet average is weighted over tickets, not an average of per-tech averages.
assert totals["avg_resolution_hours"] == 38.5
assert totals["resolved_with_timestamps"] == 4
assert totals["resolved_without_timestamps"] == 1
assert totals["unassigned_tickets"] == 2
assert totals["total_tickets"] == 12
async def test_tech_performance_reports_counts_when_timestamps_absent(client):
"""Finished tasks without ``closed_at`` yield no average but a count."""
afful = await _user_id("afful@denya.com")
await _seed_tickets([
_ticket("Completed", afful),
_ticket("Closed", afful),
_ticket("Completed", afful),
])
token = await _login(client)
resp = await client.get("/api/tickets/tech-performance", headers=_auth(token))
row = next(t for t in resp.json()["technicians"] if t["name"] == "Afful")
assert row["completed"] == 3
assert row["closed"] == 1
assert row["avg_resolution_hours"] is None
assert row["resolved_with_timestamps"] == 0
assert row["resolved_without_timestamps"] == 3
async def test_tech_performance_groups_same_name_by_user_id(client):
"""Two technicians sharing a display name stay separate rows."""
first = await _make_user("kwame.one@denya.com", "Kwame Mensah")
second = await _make_user("kwame.two@denya.com", "Kwame Mensah")
await _seed_tickets([
_ticket("Completed", first),
_ticket("Completed", second),
_ticket("Escalated", second),
])
token = await _login(client)
resp = await client.get("/api/tickets/tech-performance", headers=_auth(token))
rows = [t for t in resp.json()["technicians"] if t["name"] == "Kwame Mensah"]
assert len(rows) == 2
assert {r["technician_id"] for r in rows} == {first, second}
by_id = {r["technician_id"]: r for r in rows}
assert by_id[first]["total_assigned"] == 1
assert by_id[second]["total_assigned"] == 2
assert by_id[second]["escalated"] == 1