HH/templates/complaints/complaint_detail.html

1433 lines
69 KiB
HTML

{% extends "layouts/base.html" %}
{% load i18n %}
{% load static %}
{% load math %}
{% block title %}Complaint #{{ complaint.id|slice:":8" }} - PX360{% endblock %}
{% block extra_css %}
<style>
.complaint-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 12px;
margin-bottom: 30px;
}
.sla-countdown {
background: rgba(255,255,255,0.2);
padding: 15px;
border-radius: 8px;
text-align: center;
}
.sla-countdown.overdue {
background: #d32f2f;
}
.status-badge {
padding: 6px 16px;
border-radius: 20px;
font-size: 0.9rem;
font-weight: 600;
}
.status-open { background: #e3f2fd; color: #1976d2; }
.status-in_progress { background: #fff3e0; color: #f57c00; }
.status-resolved { background: #e8f5e9; color: #388e3c; }
.status-closed { background: #f5f5f5; color: #616161; }
.status-cancelled { background: #ffebee; color: #d32f2f; }
.severity-badge {
padding: 6px 16px;
border-radius: 20px;
font-size: 0.9rem;
font-weight: 600;
}
.severity-low { background: #e8f5e9; color: #388e3c; }
.severity-medium { background: #fff3e0; color: #f57c00; }
.severity-high { background: #ffebee; color: #d32f2f; }
.severity-critical { background: #880e4f; color: #fff; }
.timeline {
position: relative;
padding-left: 30px;
}
.timeline::before {
content: '';
position: absolute;
left: 8px;
top: 0;
bottom: 0;
width: 2px;
background: #dee2e6;
}
.timeline-item {
position: relative;
padding-bottom: 30px;
}
.timeline-item::before {
content: '';
position: absolute;
left: -26px;
top: 5px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #fff;
border: 3px solid #667eea;
z-index: 1;
}
.timeline-item.status_change::before {
border-color: #f57c00;
}
.timeline-item.assignment::before {
border-color: #1976d2;
}
.timeline-item.escalation::before {
border-color: #d32f2f;
}
.timeline-item.note::before {
border-color: #388e3c;
}
.action-card {
border-left: 4px solid #667eea;
transition: transform 0.2s;
}
.action-card:hover {
transform: translateX(5px);
}
.info-label {
font-weight: 600;
color: #6c757d;
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.info-value {
font-size: 1rem;
color: #212529;
margin-top: 4px;
}
</style>
{% endblock %}
{% block content %}
<div class="container-fluid">
<!-- Back Button -->
<div class="mb-3">
<a href="{% url 'complaints:complaint_list' %}" class="btn btn-outline-secondary btn-sm">
<i class="bi bi-arrow-left me-1"></i> {{ _("Back to Complaints")}}
</a>
</div>
<!-- Complaint Header -->
<div class="complaint-header">
<div class="row align-items-center">
<div class="col-md-8">
<div class="d-flex align-items-center mb-2">
<h3 class="mb-0 me-3">{{ complaint.title }}</h3>
<span class="status-badge status-{{ complaint.status }}">
{{ complaint.get_status_display }}
</span>
<span class="severity-badge severity-{{ complaint.severity }} ms-2">
{{ complaint.get_severity_display }}
</span>
</div>
<p class="mb-2">
<i class="bi bi-hash me-1"></i>
<strong>{{ _("ID") }}:</strong> {{ complaint.id|slice:":8" }}
<span class="mx-2">|</span>
<i class="bi bi-person-fill me-1"></i>
<strong>{{ _("Patient") }}:</strong> {{ complaint.patient.get_full_name }} ({{ _("MRN") }}: {{ complaint.patient.mrn }})
</p>
<p class="mb-0">
<i class="bi bi-hospital me-1"></i>
<strong>{{ _("Hospital") }}:</strong> {{ complaint.hospital.name_en }}
{% if complaint.department %}
<span class="mx-2">|</span>
<i class="bi bi-building me-1"></i>
<strong>{{ _("Department") }}:</strong> {{ complaint.department.name_en }}
{% endif %}
</p>
</div>
<div class="col-md-4">
<div class="sla-countdown {% if complaint.is_overdue %}overdue{% endif %}">
<div class="mb-1">
<i class="bi bi-clock-history me-1"></i>
<strong>{{ _("SLA Deadline")}}</strong>
</div>
<h4 class="mb-0">{{ complaint.due_at|date:"M d, Y H:i" }}</h4>
{% if complaint.is_overdue %}
<div class="mt-2">
<i class="bi bi-exclamation-triangle-fill me-1"></i>
<strong>{{ _("OVERDUE") }}</strong>
</div>
{% else %}
<small>{{ complaint.due_at|timeuntil }} {{ _("remaining") }}</small>
{% endif %}
</div>
</div>
</div>
</div>
<div class="row">
<!-- Main Content -->
<div class="col-lg-8">
<!-- Tabs -->
<ul class="nav nav-tabs mb-3" id="complaintTabs" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="details-tab" data-bs-toggle="tab"
data-bs-target="#details" type="button" role="tab">
<i class="bi bi-info-circle me-1"></i> {{ _("Details") }}
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="timeline-tab" data-bs-toggle="tab"
data-bs-target="#timeline" type="button" role="tab">
<i class="bi bi-clock-history me-1"></i> {{ _("Timeline") }} ({{ timeline.count }})
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="attachments-tab" data-bs-toggle="tab"
data-bs-target="#attachments" type="button" role="tab">
<i class="bi bi-paperclip me-1"></i> {{ _("Attachments") }} ({{ attachments.count }})
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="actions-tab" data-bs-toggle="tab"
data-bs-target="#actions" type="button" role="tab">
<i class="bi bi-lightning-fill me-1"></i> {{ _("PX Actions")}} ({{ px_actions.count }})
</button>
</li>
</ul>
<!-- Tab Content -->
<div class="tab-content" id="complaintTabsContent">
<!-- Details Tab -->
<div class="tab-pane fade show active" id="details" role="tabpanel">
<div class="card">
<div class="card-body">
<h5 class="card-title mb-4">{% trans "Complaint Details" %}</h5>
<div class="row mb-3">
<div class="col-md-6">
<div class="info-label">{{ _("Category") }}</div>
<div class="info-value">
<span class="badge bg-secondary">{{ complaint.get_category_display }}</span>
{% if complaint.subcategory %}
<span class="text-muted ms-2">/ {{ complaint.subcategory }}</span>
{% endif %}
</div>
</div>
<div class="col-md-6">
<div class="info-label">{{ _("Source") }}</div>
<div class="info-value">{{ complaint.get_source_display }}</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<div class="info-label">{{ _("Priority") }}</div>
<div class="info-value">
<span class="badge bg-info">{{ complaint.get_priority_display }}</span>
</div>
</div>
<div class="col-md-6">
<div class="info-label">{{ _("Encounter ID")}}</div>
<div class="info-value">
{% if complaint.encounter_id %}
{{ complaint.encounter_id }}
{% else %}
<span class="text-muted">{{ _("N/A")}}</span>
{% endif %}
</div>
</div>
</div>
{% if complaint.department %}
<div class="row mb-3">
<div class="col-md-12">
<div class="info-label">{{ _("Department") }}</div>
<div class="info-value">
<div class="d-flex align-items-center">
<i class="bi bi-building me-2"></i>
<div>
<strong>{{ complaint.department.name_en }}</strong>
{% if complaint.department.name_ar %}
<span class="text-muted ms-2">({{ complaint.department.name_ar }})</span>
{% endif %}
</div>
{% if complaint.metadata.ai_analysis.old_department %}
<span class="badge bg-info ms-auto">
<i class="bi bi-robot me-1"></i>AI Mapped
</span>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
{% if complaint.staff %}
<div class="row mb-3">
<div class="col-md-12">
<div class="info-label">{{ _("Staff Member") }}</div>
<div class="info-value">
<div class="d-flex align-items-center">
<i class="bi bi-person-badge me-2"></i>
<div>
<strong>{{ complaint.staff.first_name }} {{ complaint.staff.last_name }}</strong>
{% if complaint.staff.first_name_ar or complaint.staff.last_name_ar %}
<span class="text-muted ms-2">({{ complaint.staff.first_name_ar }} {{ complaint.staff.last_name_ar }})</span>
{% endif %}
{% if complaint.staff.job_title %}
<div class="text-muted">{{ complaint.staff.job_title }}</div>
{% endif %}
</div>
<span class="badge bg-success ms-auto">
<i class="bi bi-robot me-1"></i>AI Matched
</span>
</div>
{% if complaint.metadata.ai_analysis.extracted_staff_name %}
<small class="text-muted mt-1 d-block">
<i class="bi bi-lightning me-1"></i>
Extracted from complaint: "{{ complaint.metadata.ai_analysis.extracted_staff_name }}"
{% if complaint.metadata.ai_analysis.staff_confidence %}
(confidence: {{ complaint.metadata.ai_analysis.staff_confidence|floatformat:0 }}%)
{% endif %}
</small>
{% endif %}
</div>
</div>
</div>
{% endif %}
<!-- Staff Suggestions Section -->
{% if complaint.metadata.ai_analysis.staff_matches and user.is_px_admin %}
<div class="row mb-3">
<div class="col-md-12">
<div class="info-label">
<i class="bi bi-people me-1"></i>
Staff Suggestions
{% if complaint.metadata.ai_analysis.needs_staff_review %}
<span class="badge bg-warning ms-2">Needs Review</span>
{% endif %}
</div>
<div class="info-value">
{% if complaint.metadata.ai_analysis.extracted_staff_name %}
<p class="text-muted mb-2">
AI extracted name: <strong>"{{ complaint.metadata.ai_analysis.extracted_staff_name }}"</strong>
({% if complaint.metadata.ai_analysis.staff_match_count %}{{ complaint.metadata.ai_analysis.staff_match_count }} potential match{{ complaint.metadata.ai_analysis.staff_match_count|pluralize }}{% else %}No matches found{% endif %})
</p>
{% endif %}
<div class="list-group">
{% for staff_match in complaint.metadata.ai_analysis.staff_matches %}
<div class="list-group-item list-group-item-action {% if complaint.staff and staff_match.id == complaint.staff.id|stringformat:"s" %}list-group-item-primary{% endif %}">
<div class="d-flex justify-content-between align-items-start">
<div>
<div class="d-flex align-items-center">
<i class="bi bi-person me-2 text-primary"></i>
<strong>{{ staff_match.name_en }}</strong>
{% if staff_match.name_ar %}
<span class="text-muted ms-2">({{ staff_match.name_ar }})</span>
{% endif %}
</div>
{% if staff_match.job_title %}
<small class="text-muted">{{ staff_match.job_title }}</small>
{% endif %}
{% if staff_match.specialization %}
<small class="text-muted"> • {{ staff_match.specialization }}</small>
{% endif %}
{% if staff_match.department %}
<small class="text-muted"> • {{ staff_match.department }}</small>
{% endif %}
</div>
<div class="text-end">
<span class="badge {% if staff_match.confidence >= 0.7 %}bg-success{% elif staff_match.confidence >= 0.5 %}bg-warning{% else %}bg-danger{% endif %}">
{{ staff_match.confidence|mul:100|floatformat:0 }}% confidence
</span>
{% if complaint.staff and staff_match.id == complaint.staff.id|stringformat:"s" %}
<div class="small text-success mt-1">
<i class="bi bi-check-circle-fill"></i> Currently assigned
</div>
{% elif not complaint.staff %}
<button class="btn btn-sm btn-outline-primary mt-1" onclick="assignStaff('{{ staff_match.id }}', '{{ staff_match.name_en }}')">
<i class="bi bi-person-plus"></i> Select
</button>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
<div class="mt-3">
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#staffSelectionModal">
<i class="bi bi-search me-1"></i> Search All Staff
</button>
</div>
</div>
</div>
</div>
{% endif %}
<hr>
<div class="mb-3">
<div class="info-label">{{ _("Description") }}</div>
<div class="info-value mt-2">
<p class="mb-0">{{ complaint.description|linebreaks }}</p>
</div>
</div>
<!-- AI Analysis Section -->
{% if complaint.short_description or complaint.suggested_action %}
<hr>
<div class="mb-3">
<div class="d-flex align-items-center mb-3">
<div class="info-label mb-0 me-2">
<i class="bi bi-robot me-1"></i>AI Analysis
</div>
<span class="badge bg-info">AI Generated</span>
</div>
<!-- Emotion Analysis -->
{% if complaint.emotion %}
<div class="mb-3">
<div class="info-label" style="font-size: 0.8rem;">Emotion Analysis</div>
<div class="card mb-0" style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-left: 4px solid #6c757d;">
<div class="card-body py-2">
<div class="row align-items-center mb-2">
<div class="col-md-6">
<span class="badge bg-{{ complaint.get_emotion_badge_class }} me-2">
<i class="bi bi-emoji-frown me-1"></i>{{ complaint.get_emotion_display }}
</span>
</div>
<div class="col-md-6 text-md-end">
<small class="text-muted">Confidence: {{ complaint.emotion_confidence|mul:100|floatformat:0 }}%</small>
</div>
</div>
<div class="mb-1">
<div class="d-flex justify-content-between mb-1">
<small class="text-muted">Intensity</small>
<small>{{ complaint.emotion_intensity|floatformat:2 }} / 1.0</small>
</div>
<div class="progress" style="height: 6px;">
{% if complaint.emotion == 'anger' %}
<div class="progress-bar bg-danger" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
{% elif complaint.emotion == 'sadness' %}
<div class="progress-bar bg-primary" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
{% elif complaint.emotion == 'confusion' %}
<div class="progress-bar bg-warning" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
{% elif complaint.emotion == 'fear' %}
<div class="progress-bar bg-info" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
{% else %}
<div class="progress-bar bg-secondary" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
{% endif %}
{% if complaint.short_description %}
<div class="mb-3">
<div class="info-label" style="font-size: 0.8rem;">Summary</div>
<div class="alert alert-light border-info mb-0" style="background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);">
<i class="bi bi-info-circle me-1 text-info"></i>
<small>{{ complaint.short_description }}</small>
</div>
</div>
{% endif %}
{% if complaint.suggested_action %}
<div class="mb-0">
<div class="info-label" style="font-size: 0.8rem;">Suggested Action</div>
<div class="alert alert-success mb-0" style="background: linear-gradient(135deg, #e8f5e9 0%, #e1f5fe 100%); border-color: #4caf50;">
<i class="bi bi-lightning me-1 text-success"></i>
<small>{{ complaint.suggested_action }}</small>
</div>
<button type="button" class="btn btn-sm btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#createActionModal">
<i class="bi bi-plus-circle me-1"></i> Create PX Action
</button>
</div>
{% endif %}
</div>
{% endif %}
{% if complaint.resolution %}
<hr>
<div class="mb-3">
<div class="info-label">{{ _("Resolution") }}</div>
<div class="info-value mt-2">
<div class="alert alert-success">
<p class="mb-2">{{ complaint.resolution|linebreaks }}</p>
<small class="text-muted">
{{ _("Resolved by")}} {{ complaint.resolved_by.get_full_name }}
{{ _("on") }} {{ complaint.resolved_at|date:"M d, Y H:i" }}
</small>
</div>
</div>
</div>
{% endif %}
<hr>
<div class="row">
<div class="col-md-6">
<div class="info-label">{{ _("Created") }}</div>
<div class="info-value">{{ complaint.created_at|date:"M d, Y H:i" }}</div>
</div>
<div class="col-md-6">
<div class="info-label">{{ _("Last Updated")}}</div>
<div class="info-value">{{ complaint.updated_at|date:"M d, Y H:i" }}</div>
</div>
</div>
</div>
</div>
</div>
<!-- Timeline Tab -->
<div class="tab-pane fade" id="timeline" role="tabpanel">
<div class="card">
<div class="card-body">
<h5 class="card-title mb-4">{% trans "Activity Timeline" %}</h5>
{% if timeline %}
<div class="timeline">
{% for update in timeline %}
<div class="timeline-item {{ update.update_type }}">
<div class="card mb-3">
<div class="card-body">
<div class="d-flex justify-content-between align-items-start mb-2">
<div>
<span class="badge bg-primary">{{ update.get_update_type_display }}</span>
{% if update.created_by %}
<span class="text-muted ms-2">
by {{ update.created_by.get_full_name }}
</span>
{% endif %}
</div>
<small class="text-muted">
{{ update.created_at|date:"M d, Y H:i" }}
</small>
</div>
<p class="mb-0">{{ update.message }}</p>
{% if update.old_status and update.new_status %}
<div class="mt-2">
<span class="status-badge status-{{ update.old_status }}">
{{ update.old_status }}
</span>
<i class="bi bi-arrow-right mx-2"></i>
<span class="status-badge status-{{ update.new_status }}">
{{ update.new_status }}
</span>
</div>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="text-center py-5">
<i class="bi bi-clock-history" style="font-size: 3rem; color: #ccc;"></i>
<p class="text-muted mt-3">{{ _("No timeline entries yet")}}</p>
</div>
{% endif %}
</div>
</div>
</div>
<!-- Attachments Tab -->
<div class="tab-pane fade" id="attachments" role="tabpanel">
<div class="card">
<div class="card-body">
<h5 class="card-title mb-4">{% trans "Attachments" %}</h5>
{% if attachments %}
<div class="list-group">
{% for attachment in attachments %}
<div class="list-group-item">
<div class="d-flex justify-content-between align-items-center">
<div>
<i class="bi bi-file-earmark me-2"></i>
<strong>{{ attachment.filename }}</strong>
<br>
<small class="text-muted">
Uploaded by {{ attachment.uploaded_by.get_full_name }}
on {{ attachment.created_at|date:"M d, Y H:i" }}
({{ attachment.file_size|filesizeformat }})
</small>
{% if attachment.description %}
<br>
<small>{{ attachment.description }}</small>
{% endif %}
</div>
<a href="{{ attachment.file.url }}" class="btn btn-sm btn-outline-primary"
target="_blank" download>
<i class="bi bi-download"></i>
</a>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="text-center py-5">
<i class="bi bi-paperclip" style="font-size: 3rem; color: #ccc;"></i>
<p class="text-muted mt-3">{{ _("No attachments")}}</p>
</div>
{% endif %}
</div>
</div>
</div>
<!-- PX Actions Tab -->
<div class="tab-pane fade" id="actions" role="tabpanel">
<div class="card">
<div class="card-body">
<h5 class="card-title mb-4">{% trans "Related PX Actions" %}</h5>
{% if px_actions %}
{% for action in px_actions %}
<div class="card action-card mb-3">
<div class="card-body">
<div class="d-flex justify-content-between align-items-start">
<div>
<h6 class="mb-1">{{ action.title }}</h6>
<p class="text-muted mb-2">{{ action.description|truncatewords:20 }}</p>
<div>
<span class="badge bg-{{ action.status }}">{{ action.get_status_display }}</span>
<span class="badge bg-secondary ms-1">{{ action.get_priority_display }}</span>
</div>
</div>
<a href="{% url 'actions:action_detail' action.id %}"
class="btn btn-sm btn-outline-primary">
{{ _("View") }} <i class="bi bi-arrow-right ms-1"></i>
</a>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="text-center py-5">
<i class="bi bi-lightning" style="font-size: 3rem; color: #ccc;"></i>
<p class="text-muted mt-3">{{ _("No PX actions created yet")}}</p>
</div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
<!-- Sidebar Actions -->
<div class="col-lg-4">
<!-- Quick Actions -->
{% if can_edit %}
<div class="card mb-3">
<div class="card-header bg-primary text-white">
<h6 class="mb-0"><i class="bi bi-lightning-fill me-2"></i>{% trans "Quick Actions" %}</h6>
</div>
<div class="card-body">
{% if user.is_px_admin %}
<!-- Change Staff (PX Admin only) -->
<div class="mb-3">
<label class="form-label">{% trans "Change Staff" %}</label>
<button type="button" class="btn btn-outline-info w-100" data-bs-toggle="modal" data-bs-target="#staffSelectionModal">
<i class="bi bi-person-badge me-1"></i> {{ _("Assign/Change Staff")}}
</button>
{% if complaint.metadata.ai_analysis.needs_staff_review %}
<small class="text-warning">
<i class="bi bi-exclamation-triangle me-1"></i>
This complaint needs staff review
</small>
{% endif %}
</div>
<hr>
{% endif %}
<!-- Change Department -->
{% if can_edit and hospital_departments %}
<form method="post" action="{% url 'complaints:complaint_change_department' complaint.id %}" class="mb-3">
{% csrf_token %}
<label class="form-label">{% trans "Change Department" %}</label>
<div class="input-group">
<select name="department_id" class="form-select" required>
<option value="">{{ _("Select department...")}}</option>
{% for dept in hospital_departments %}
<option value="{{ dept.id }}"
{% if complaint.department and complaint.department.id == dept.id %}selected{% endif %}>
{{ dept.name_en }}
{% if dept.name_ar %}({{ dept.name_ar }}){% endif %}
</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary">
<i class="bi bi-building"></i>
</button>
</div>
</form>
{% endif %}
<!-- Assign -->
<form method="post" action="{% url 'complaints:complaint_assign' complaint.id %}" class="mb-3">
{% csrf_token %}
<label class="form-label">{% trans "Assign To" %}</label>
<div class="input-group">
<select name="user_id" class="form-select" required>
<option value="">{{ _("Select user...")}}</option>
{% for user_obj in assignable_users %}
<option value="{{ user_obj.id }}"
{% if complaint.assigned_to and complaint.assigned_to.id == user_obj.id %}selected{% endif %}>
{{ user_obj.get_full_name }}
</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary">
<i class="bi bi-person-check"></i>
</button>
</div>
</form>
<!-- Change Status -->
<form method="post" action="{% url 'complaints:complaint_change_status' complaint.id %}" class="mb-3">
{% csrf_token %}
<label class="form-label">{% trans "Change Status" %}</label>
<select name="status" class="form-select mb-2" required>
{% for value, label in status_choices %}
<option value="{{ value }}" {% if complaint.status == value %}selected{% endif %}>
{{ label }}
</option>
{% endfor %}
</select>
<textarea name="note" class="form-control mb-2" rows="2"
placeholder="{% trans 'Optional note...' %}"></textarea>
<button type="submit" class="btn btn-primary w-100">
<i class="bi bi-arrow-repeat me-1"></i> {{ _("Update Status")}}
</button>
</form>
<!-- Send Notification -->
<button type="button" class="btn btn-info w-100 mb-2" data-bs-toggle="modal"
data-bs-target="#sendNotificationModal">
<i class="bi bi-envelope me-1"></i> {{ _("Send Notification") }}
</button>
<!-- Escalate -->
<button type="button" class="btn btn-danger w-100" data-bs-toggle="modal"
data-bs-target="#escalateModal">
<i class="bi bi-exclamation-triangle me-1"></i> {{ _("Escalate") }}
</button>
</div>
</div>
{% endif %}
<!-- Add Note -->
<div class="card mb-3">
<div class="card-header bg-success text-white">
<h6 class="mb-0"><i class="bi bi-chat-left-text me-2"></i>{% trans "Add Note" %}</h6>
</div>
<div class="card-body">
<form method="post" action="{% url 'complaints:complaint_add_note' complaint.id %}">
{% csrf_token %}
<textarea name="note" class="form-control mb-2" rows="3"
placeholder="{% trans 'Enter your note...' %}" required></textarea>
<button type="submit" class="btn btn-success w-100">
<i class="bi bi-plus-circle me-1"></i> {{ _("Add Note")}}
</button>
</form>
</div>
</div>
<!-- Assignment Info -->
<div class="card mb-3">
<div class="card-header">
<h6 class="mb-0"><i class="bi bi-info-circle me-2"></i>{% trans "Assignment Info" %}</h6>
</div>
<div class="card-body">
<div class="mb-3">
<div class="info-label">{{ _("Assigned To")}}</div>
<div class="info-value">
{% if complaint.assigned_to %}
{{ complaint.assigned_to.get_full_name }}
<br>
<small class="text-muted">
Assigned {{ complaint.assigned_at|date:"M d, Y H:i" }}
</small>
{% else %}
<span class="text-muted">{{ _("Unassigned") }}</span>
{% endif %}
</div>
</div>
{% if complaint.resolved_by %}
<div class="mb-3">
<div class="info-label">{{ _("Resolved By")}}</div>
<div class="info-value">
{{ complaint.resolved_by.get_full_name }}
<br>
<small class="text-muted">
{{ complaint.resolved_at|date:"M d, Y H:i" }}
</small>
</div>
</div>
{% endif %}
{% if complaint.closed_by %}
<div class="mb-0">
<div class="info-label">{{ _("Closed By")}}</div>
<div class="info-value">
{{ complaint.closed_by.get_full_name }}
<br>
<small class="text-muted">
{{ complaint.closed_at|date:"M d, Y H:i" }}
</small>
</div>
</div>
{% endif %}
</div>
</div>
<!-- Resolution Survey -->
{% if complaint.resolution_survey %}
<div class="card">
<div class="card-header bg-info text-white">
<h6 class="mb-0"><i class="bi bi-clipboard-check me-2"></i>{% trans "Resolution Survey" %}</h6>
</div>
<div class="card-body">
<p class="mb-2">
<strong>{{ _("Status") }}:</strong>
<span class="badge bg-{{ complaint.resolution_survey.status }}">
{{ complaint.resolution_survey.get_status_display }}
</span>
</p>
{% if complaint.resolution_survey.score %}
<p class="mb-2">
<strong>{{ _("Score") }}:</strong> {{ complaint.resolution_survey.score }}/100
</p>
{% endif %}
<a href="{% url 'surveys:survey_instance_detail' complaint.resolution_survey.id %}"
class="btn btn-sm btn-outline-info">
{{ _("View Survey")}} <i class="bi bi-arrow-right ms-1"></i>
</a>
</div>
</div>
{% endif %}
</div>
</div>
</div>
<!-- Escalate Modal -->
<div class="modal fade" id="escalateModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" action="{% url 'complaints:complaint_escalate' complaint.id %}">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title">{% trans "Escalate Complaint" %}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="alert alert-warning">
<i class="bi bi-exclamation-triangle me-2"></i>
{{ _("This will escalate")}} complaint to higher management}}.
</div>
<div class="mb-3">
<label class="form-label">{% trans "Reason for Escalation" %}</label>
<textarea name="reason" class="form-control" rows="3"
placeholder="{% trans 'Explain why this complaint needs escalation...' %}" required></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Cancel" %}</button>
<button type="submit" class="btn btn-danger">
<i class="bi bi-exclamation-triangle me-1"></i> {{ _("Escalate") }}
</button>
</div>
</form>
</div>
</div>
</div>
<!-- Create PX Action Modal -->
<div class="modal fade" id="createActionModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-lightning-fill me-2"></i>Create PX Action from AI Suggestion
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="alert alert-info">
<i class="bi bi-info-circle me-2"></i>
This will create a PX Action based on the AI-suggested action for this complaint.
</div>
<div class="mb-3">
<label class="form-label">Auto-mapped Category</label>
<div class="input-group">
<span class="input-group-text">
<i class="bi bi-tag"></i>
</span>
<input type="text" id="autoMappedCategory" class="form-control" readonly
value="{% if complaint.category %}{{ complaint.category.name_en }}{% else %}Other{% endif %}">
</div>
<small class="text-muted">Category automatically mapped from complaint category</small>
</div>
<div class="mb-3">
<label class="form-label">Assign To (Optional)</label>
<select id="actionAssignTo" class="form-select">
<option value="">Leave unassigned</option>
{% for user_obj in assignable_users %}
<option value="{{ user_obj.id }}">{{ user_obj.get_full_name }}</option>
{% endfor %}
</select>
<small class="text-muted">If left unassigned, you can assign the action later.</small>
</div>
<div class="mb-0">
<label class="form-label">Action Description</label>
<div class="alert alert-success mb-0">
<small>{{ complaint.suggested_action }}</small>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" id="createActionBtn" class="btn btn-primary" onclick="createAction()">
<i class="bi bi-plus-circle me-1"></i>Create Action
</button>
</div>
</div>
</div>
</div>
<!-- Staff Selection Modal -->
<div class="modal fade" id="staffSelectionModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-person-badge me-2"></i>Select Staff Member
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<!-- Department Filter -->
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">Filter by Department</label>
<select id="staffDepartmentFilter" class="form-select">
<option value="">All Departments</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Search Staff</label>
<input type="text" id="staffSearchInput" class="form-control" placeholder="Search by name or job title...">
</div>
</div>
<!-- Staff List -->
<div id="staffListContainer" class="border rounded" style="max-height: 400px; overflow-y: auto;">
<div class="text-center py-4">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" id="assignSelectedStaffBtn" class="btn btn-primary" onclick="assignSelectedStaff()" disabled>
<i class="bi bi-person-check me-1"></i>Assign Selected Staff
</button>
</div>
</div>
</div>
</div>
<!-- Send Notification Modal -->
<div class="modal fade" id="sendNotificationModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-envelope me-2"></i>Send Complaint Notification
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<!-- AI Summary (EDITABLE) -->
<div class="mb-3">
<label class="form-label">
<i class="bi bi-robot me-1"></i>
AI Summary
<small class="text-muted">(you can edit this before sending)</small>
</label>
<textarea id="emailMessage" class="form-control" rows="5"
placeholder="Enter message to send...">{{ complaint.short_description }}</textarea>
<small class="text-muted">
This is AI-generated summary. You can edit it before sending.
</small>
</div>
<!-- Recipient Information -->
<div class="card mb-3">
<div class="card-body">
<h6 class="card-title">
<i class="bi bi-person-check me-1"></i>Recipient
</h6>
{% if complaint.staff and complaint.staff.user %}
<!-- Staff has user account - will receive email -->
<div class="alert alert-success mb-2">
<i class="bi bi-check-circle-fill me-1"></i>
<strong>Primary Recipient:</strong> {{ complaint.staff.get_full_name }}
{% if complaint.staff.job_title %}
<br><small class="text-muted">{{ complaint.staff.job_title }}</small>
{% endif %}
</div>
{% elif complaint.staff %}
<!-- Staff exists but has no user account -->
<div class="alert alert-warning mb-2">
<i class="bi bi-exclamation-triangle-fill me-1"></i>
<strong>Staff Member Assigned:</strong> {{ complaint.staff.get_full_name }}
{% if complaint.staff.job_title %}
<br><small class="text-muted">{{ complaint.staff.job_title }}</small>
{% endif %}
<hr class="my-2">
<small class="text-muted">
<i class="bi bi-info-circle me-1"></i>
This staff member has no user account in the system.
</small>
</div>
{% if complaint.department and complaint.department.manager %}
<!-- Department manager is the actual recipient -->
<div class="alert alert-info mb-0">
<i class="bi bi-person-badge me-1"></i>
<strong>Actual Recipient:</strong> {{ complaint.department.manager.get_full_name }}
<br><small class="text-muted">Department Head of {{ complaint.department.name_en }}</small>
</div>
{% else %}
<!-- No fallback recipient -->
<div class="alert alert-danger mb-0">
<i class="bi bi-x-circle-fill me-1"></i>
<strong>No recipient available</strong>
<br><small>The assigned staff has no user account and no department manager is set.</small>
</div>
{% endif %}
{% elif complaint.department and complaint.department.manager %}
<!-- No staff, but department manager exists -->
<div class="alert alert-info mb-0">
<i class="bi bi-person-badge me-1"></i>
<strong>Department Head:</strong> {{ complaint.department.manager.get_full_name }}
<br><small class="text-muted">Manager of {{ complaint.department.name_en }}</small>
</div>
{% else %}
<!-- No recipient at all -->
<div class="alert alert-danger mb-0">
<i class="bi bi-exclamation-triangle-fill me-1"></i>
<strong>No recipient available</strong>
<br><small>No staff or department manager assigned to this complaint.</small>
</div>
{% endif %}
</div>
</div>
<!-- Optional Additional Message -->
<div class="mb-3">
<label class="form-label">
Additional Message (Optional)
</label>
<textarea id="additionalMessage" class="form-control" rows="3"
placeholder="Add any additional notes to send..."></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Cancel
</button>
<button type="button" id="sendNotificationBtn" class="btn btn-primary"
onclick="sendNotification()">
<i class="bi bi-send me-1"></i>Send Email
</button>
</div>
</div>
</div>
</div>
<script>
let selectedStaffId = null;
let allHospitalStaff = [];
let currentLanguage = document.documentElement.lang || 'en';
// Load hospital staff when modal opens
document.getElementById('staffSelectionModal').addEventListener('shown.bs.modal', function() {
loadHospitalDepartments();
loadHospitalStaff();
});
// Load hospital departments
function loadHospitalDepartments() {
const hospitalId = '{{ complaint.hospital.id }}';
const departmentSelect = document.getElementById('staffDepartmentFilter');
fetch(`/organizations/api/departments/?hospital=${hospitalId}`, {
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => {
// Clear existing options except the first one
departmentSelect.innerHTML = '<option value="">All Departments</option>';
// Populate with departments
data.results.forEach(dept => {
const option = document.createElement('option');
option.value = dept.id;
const deptName = currentLanguage === 'ar' && dept.name_ar ? dept.name_ar : dept.name_en;
option.textContent = deptName;
departmentSelect.appendChild(option);
});
})
.catch(error => {
console.error('Error loading departments:', error);
});
}
// Load hospital staff from API
function loadHospitalStaff(departmentId = null, search = '') {
const container = document.getElementById('staffListContainer');
let url = `/complaints/api/complaints/{{ complaint.id }}/hospital_staff/`;
const params = new URLSearchParams();
if (departmentId) params.append('department_id', departmentId);
if (search) params.append('search', search);
if (params.toString()) {
url += '?' + params.toString();
}
container.innerHTML = `
<div class="text-center py-4">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
`;
fetch(url, {
credentials: 'same-origin',
headers: {
'X-CSRFToken': getCookie('csrftoken')
}
})
.then(response => response.json())
.then(data => {
allHospitalStaff = data.staff || [];
renderStaffList(allHospitalStaff);
})
.catch(error => {
console.error('Error loading staff:', error);
container.innerHTML = `
<div class="alert alert-danger m-3">
<i class="bi bi-exclamation-triangle me-2"></i>
Failed to load staff. Please try again.
</div>
`;
});
}
// Render staff list
function renderStaffList(staffList) {
const container = document.getElementById('staffListContainer');
if (!staffList || staffList.length === 0) {
container.innerHTML = `
<div class="text-center py-4 text-muted">
<i class="bi bi-people" style="font-size: 3rem;"></i>
<p class="mt-3">No staff found</p>
</div>
`;
return;
}
let html = '<div class="list-group list-group-flush">';
// Group by department
const grouped = {};
staffList.forEach(staff => {
const dept = staff.department || 'No Department';
if (!grouped[dept]) grouped[dept] = [];
grouped[dept].push(staff);
});
// Render groups
for (const [department, staffMembers] of Object.entries(grouped)) {
html += `<div class="list-group-item bg-light fw-bold"><i class="bi bi-building me-2"></i>${department}</div>`;
staffMembers.forEach(staff => {
html += `
<div class="list-group-item list-group-item-action staff-item"
data-staff-id="${staff.id}"
data-staff-name="${staff.name_en}"
onclick="selectStaff('${staff.id}', '${staff.name_en.replace(/'/g, "\\'")}')">
<div class="form-check">
<input class="form-check-input" type="radio" name="selectedStaff"
id="staff_${staff.id}" value="${staff.id}"
${selectedStaffId === staff.id ? 'checked' : ''}>
<label class="form-check-label w-100 cursor-pointer" for="staff_${staff.id}">
<div>
<strong>${staff.name_en}</strong>
${staff.name_ar ? `<span class="text-muted ms-2">(${staff.name_ar})</span>` : ''}
</div>
<small class="text-muted">
${staff.job_title || ''}
${staff.specialization ? '• ' + staff.specialization : ''}
</small>
</label>
</div>
</div>
`;
});
}
html += '</div>';
container.innerHTML = html;
}
// Select staff from list
function selectStaff(staffId, staffName) {
selectedStaffId = staffId;
// Update radio buttons
document.querySelectorAll('input[name="selectedStaff"]').forEach(radio => {
radio.checked = (radio.value === staffId);
});
// Enable assign button
document.getElementById('assignSelectedStaffBtn').disabled = false;
}
// Assign staff directly from suggestions
function assignStaff(staffId, staffName) {
if (!confirm(`Assign ${staffName} to this complaint?`)) {
return;
}
const data = {
staff_id: staffId,
reason: 'Selected from AI suggestions'
};
fetch(`/complaints/api/complaints/{{ complaint.id }}/assign_staff/`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
if (result.message) {
alert('Staff assigned successfully!');
location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
}
})
.catch(error => {
console.error('Error:', error);
alert('Failed to assign staff. Please try again.');
});
}
// Assign selected staff from modal
function assignSelectedStaff() {
if (!selectedStaffId) {
alert('Please select a staff member first.');
return;
}
const staffName = document.querySelector(`input[name="selectedStaff"]:checked`)?.closest('.staff-item')?.dataset?.staffName || 'selected staff';
const reason = prompt('Reason for assignment (optional):', 'Manual selection from hospital staff list');
const data = {
staff_id: selectedStaffId,
reason: reason || 'Manual selection from hospital staff list'
};
const btn = document.getElementById('assignSelectedStaffBtn');
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Assigning...';
fetch(`/complaints/api/complaints/{{ complaint.id }}/assign_staff/`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
if (result.message) {
alert('Staff assigned successfully!');
location.reload();
} else {
alert('Error: ' + (result.error || 'Unknown error'));
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-person-check me-1"></i>Assign Selected Staff';
}
})
.catch(error => {
console.error('Error:', error);
alert('Failed to assign staff. Please try again.');
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-person-check me-1"></i>Assign Selected Staff';
});
}
// Department filter change handler
document.getElementById('staffDepartmentFilter')?.addEventListener('change', function(e) {
const departmentId = e.target.value || null;
const search = document.getElementById('staffSearchInput').value.trim();
loadHospitalStaff(departmentId, search);
});
// Search input handler (debounced)
let searchTimeout;
document.getElementById('staffSearchInput')?.addEventListener('input', function(e) {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
const departmentId = document.getElementById('staffDepartmentFilter').value || null;
const search = e.target.value.trim();
loadHospitalStaff(departmentId, search);
}, 300);
});
function createAction() {
const assignTo = document.getElementById('actionAssignTo').value;
const btn = document.getElementById('createActionBtn');
const data = {};
if (assignTo) {
data.assigned_to = assignTo;
}
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Creating...';
fetch(`/complaints/api/complaints/{{ complaint.id }}/create_action_from_ai/`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
if (data.action_id) {
// Redirect to action detail page
window.location.href = `/actions/${data.action_id}/`;
} else {
alert('Error: ' + (data.error || 'Unknown error'));
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-plus-circle me-1"></i>Create Action';
}
})
.catch(error => {
console.error('Error:', error);
alert('Failed to create action. Please try again.');
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-plus-circle me-1"></i>Create Action';
});
}
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sendNotification() {
const btn = document.getElementById('sendNotificationBtn');
const emailMessage = document.getElementById('emailMessage').value;
const additionalMessage = document.getElementById('additionalMessage').value;
// Validate email message is not empty
if (!emailMessage.trim()) {
alert('Please enter a message to send.');
return;
}
// Disable button and show loading
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
// Get CSRF token
const csrftoken = getCookie('csrftoken');
fetch(`/complaints/api/complaints/{{ complaint.id }}/send_notification/`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken
},
body: JSON.stringify({
email_message: emailMessage,
additional_message: additionalMessage
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Email sent successfully!');
// Close modal
const modal = bootstrap.Modal.getInstance(document.getElementById('sendNotificationModal'));
modal.hide();
// Reload page to show timeline entry
location.reload();
} else {
alert('Error: ' + (data.error || 'Unknown error'));
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-send me-1"></i>Send Email';
}
})
.catch(error => {
console.error('Error:', error);
alert('Failed to send email. Please try again.');
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-send me-1"></i>Send Email';
});
}
</script>
{% endblock %}