Spaces:
Sleeping
Sleeping
Download templates/patient_edit.html from alisaleem97/NexLab_System: direct link, hf CLI and curl.
- Browser
- Download file 60.9 kB
-
https://huggingface.co/spaces/alisaleem97/NexLab_System/resolve/main/templates/patient_edit.html
- Command line
-
hf download hf://spaces/alisaleem97/NexLab_System/templates/patient_edit.html
-
curl -L -o patient_edit.html https://huggingface.co/spaces/alisaleem97/NexLab_System/resolve/main/templates/patient_edit.html
60.9 kB
<!-- templates/patient_edit.html -->
{% extends "base.html" %}
{% block title %}Edit Patient - NexLab{% endblock %}
{% block page_title %}Edit Patient Data{% endblock %}
{% block content %}
<!-- Tom Select CSS -->
<link href="/static/vendor/tom-select/tom-select.css" rel="stylesheet">
<style>
.popup-notification {
position: fixed;
top: 20px;
right: 20px;
padding: 16px 24px;
border-radius: 8px;
color: white;
font-weight: 500;
z-index: 9999;
animation: slideIn 0.3s ease-out;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.popup-success { background: #10b981; }
.popup-error { background: #ef4444; }
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.ts-wrapper { position: relative !important; width: 100%; z-index: 100; }
.ts-dropdown {
max-height: 250px !important;
overflow-y: auto !important;
z-index: 9999 !important;
position: absolute !important;
width: 100% !important;
}
</style>
<!-- Popup Container -->
<div id="popupContainer"></div>
<div class="bg-white rounded-xl shadow-sm border border-slate-200">
<!-- Header -->
<div class="p-6 border-b border-slate-200">
<div class="flex items-center justify-between flex-wrap gap-4">
<div>
<h3 class="text-lg font-semibold text-slate-800">Edit Patient</h3>
<p class="text-sm text-slate-500">Patient ID: <strong class="font-mono">{{ patient.patient_id }}</strong></p>
</div>
<div class="flex gap-3">
<a href="/patients" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-lg text-sm font-medium">← Back</a>
<button type="button" onclick="printReceipt('{{ patient.patient_id }}')" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg text-sm font-medium">📄 Print Receipt</button>
<button type="button" onclick="printBarcode('{{ patient.patient_id }}')" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium">🏷️ Print Barcode</button>
</div>
</div>
</div>
<form method="POST" action="/patients/update/{{ patient.patient_id }}?visit_id={{ latest_visit.visit_id }}" id="editForm">
<div class="p-6 space-y-6">
<!-- Main Information -->
<div>
<h4 class="text-md font-semibold text-slate-700 mb-4">Main Information</h4>
<div class="flex flex-wrap items-start gap-x-4 gap-y-4">
<div class="w-full sm:w-24">
<label class="block text-sm font-medium text-slate-700 mb-1">Patient ID</label>
<input type="text" value="{{ patient.patient_id }}" readonly
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 bg-slate-100 font-mono focus:outline-none">
</div>
<div class="w-full sm:min-w-[16rem] flex-1 relative">
<label class="block text-sm font-medium text-slate-700 mb-1">Patient Name *</label>
<input type="text" id="full_name" name="full_name" value="{{ patient.full_name }}" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<!-- ✅ Gender Warning Message -->
<div id="genderWarning" class="hidden absolute top-full left-0 mt-1 w-full z-10 p-3 bg-green-50 border border-green-200 rounded-lg shadow-md flex items-center">
<span class="mr-2 text-lg">ℹ️</span>
<span class="font-medium text-sm text-green-800">تنبيه: الجنس قد لا يتطابق مع الاسم المدخل</span>
</div>
</div>
<div class="w-full sm:w-40">
<label class="block text-sm font-medium text-slate-700 mb-1">Gender *</label>
<select id="gender" name="gender" required onchange="verifyGender(); this.className = this.options[this.selectedIndex].className + ' w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none';"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none {{ 'text-blue-600 bg-blue-50 font-medium' if patient.gender == 'male' else 'text-pink-600 bg-pink-50 font-medium' }}">
<option value="">Select...</option>
<option value="male" class="text-blue-600 bg-blue-50 font-medium" {% if patient.gender == 'male' %}selected{% endif %}>Male</option>
<option value="female" class="text-pink-600 bg-pink-50 font-medium" {% if patient.gender == 'female' %}selected{% endif %}>Female</option>
</select>
</div>
<div class="w-full sm:w-24">
<label class="block text-sm font-medium text-slate-700 mb-1">Age *</label>
<input type="number" id="age" name="age" value="{{ patient.age }}" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="w-full sm:w-40">
<label class="block text-sm font-medium text-slate-700 mb-1">Date of Birth</label>
<input type="date" id="date_of_birth" name="date_of_birth" value="{{ patient.date_of_birth.strftime('%Y-%m-%d') if patient.date_of_birth else '' }}" onchange="calculateAge()"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="w-full sm:w-32">
<label class="block text-sm font-medium text-slate-700 mb-1">Age Unit *</label>
<select id="age_unit" name="age_unit" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<option value="year" {% if patient.age_unit == 'year' %}selected{% endif %}>Years</option>
<option value="month" {% if patient.age_unit == 'month' %}selected{% endif %}>Months</option>
<option value="day" {% if patient.age_unit == 'day' %}selected{% endif %}>Days</option>
</select>
</div>
<div class="w-full sm:w-40">
<label class="block text-sm font-medium text-slate-700 mb-1">Phone Key *</label>
<select id="phone_key" name="phone_key" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<option value="+964" {% if patient.phone_key == '+964' %}selected{% endif %}>Iraq (+964)</option>
<option value="+1" {% if patient.phone_key == '+1' %}selected{% endif %}>USA (+1)</option>
<option value="+44" {% if patient.phone_key == '+44' %}selected{% endif %}>UK (+44)</option>
<option value="+966" {% if patient.phone_key == '+966' %}selected{% endif %}>Saudi Arabia (+966)</option>
<option value="+971" {% if patient.phone_key == '+971' %}selected{% endif %}>UAE (+971)</option>
<option value="+965" {% if patient.phone_key == '+965' %}selected{% endif %}>Kuwait (+965)</option>
<option value="+968" {% if patient.phone_key == '+968' %}selected{% endif %}>Oman (+968)</option>
<option value="+973" {% if patient.phone_key == '+973' %}selected{% endif %}>Bahrain (+973)</option>
<option value="+974" {% if patient.phone_key == '+974' %}selected{% endif %}>Qatar (+974)</option>
<option value="+962" {% if patient.phone_key == '+962' %}selected{% endif %}>Jordan (+962)</option>
<option value="+961" {% if patient.phone_key == '+961' %}selected{% endif %}>Lebanon (+961)</option>
<option value="+963" {% if patient.phone_key == '+963' %}selected{% endif %}>Syria (+963)</option>
<option value="+98" {% if patient.phone_key == '+98' %}selected{% endif %}>Iran (+98)</option>
<option value="+90" {% if patient.phone_key == '+90' %}selected{% endif %}>Turkey (+90)</option>
<option value="+20" {% if patient.phone_key == '+20' %}selected{% endif %}>Egypt (+20)</option>
</select>
</div>
<div class="w-full sm:w-48">
<label class="block text-sm font-medium text-slate-700 mb-1">Phone Number *</label>
<input type="text" id="phone_number" name="phone_number" value="{{ patient.phone_number }}" required minlength="10"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="basis-full h-0 m-0 p-0 hidden sm:block"></div>
<div class="w-full sm:w-24">
<label class="block text-sm font-medium text-slate-700 mb-1">Weight (kg) *</label>
<input type="number" id="weight" name="weight" value="{{ patient.weight }}" step="0.1" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="w-full sm:w-24">
<label class="block text-sm font-medium text-slate-700 mb-1">Height (cm) *</label>
<input type="number" id="height" name="height" value="{{ patient.height }}" step="0.1" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="w-full sm:w-48">
<label class="block text-sm font-medium text-slate-700 mb-1">Province *</label>
<select id="province_id" name="province_id" required onchange="loadRegions()"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<option value="">Select Province...</option>
{% for province in provinces %}
<option value="{{ province.id }}" {% if patient.province_id == province.id %}selected{% endif %}>{{ province.province_name }}</option>
{% endfor %}
</select>
</div>
<div class="w-full sm:w-48">
<label class="block text-sm font-medium text-slate-700 mb-1">Region *</label>
<select id="region_id" name="region_id" required {% if not patient.province_id %}disabled{% endif %}
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none {% if not patient.province_id %}bg-slate-100{% endif %}">
<option value="">Select Region...</option>
{% for region in regions %}
<option value="{{ region.id }}" {% if patient.region_id == region.id %}selected{% endif %}>{{ region.region_name }}</option>
{% endfor %}
</select>
</div>
<div class="w-full sm:w-32">
<label class="block text-sm font-medium text-slate-700 mb-1">Fasting Time (hr)</label>
<input type="number" id="fasting_time" name="fasting_time" value="{{ patient.fasting_time or '' }}" min="0"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="w-full sm:flex-1">
<label class="block text-sm font-medium text-slate-700 mb-1">Note *</label>
<input type="text" id="note" name="note" value="{{ patient.note or '' }}" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
</div>
</div>
<!-- ✅ CHANGE: Centered "More" Button -->
<div class="text-center py-4">
<button type="button" onclick="toggleMoreInfo()"
class="bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-2 rounded-lg text-sm font-medium transition duration-200 inline-flex items-center gap-2">
<span>More</span>
<svg id="moreIcon" class="w-4 h-4 transform transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</button>
<div id="moreInfoSection" class="hidden mt-4 pt-4 border-t border-slate-200 text-left">
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Email</label>
<input type="email" id="email" name="email" value="{{ patient.email or '' }}"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Diagnosis</label>
<input type="text" id="diagnosis" name="diagnosis" value="{{ patient.diagnosis or '' }}"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Symptoms</label>
<input type="text" id="symptoms" name="symptoms" value="{{ patient.symptoms or '' }}"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Therapy</label>
<input type="text" id="therapy" name="therapy" value="{{ patient.therapy or '' }}"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Partner</label>
<select id="partner_id" name="partner_id"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<option value="">Select Partner...</option>
{% for partner in partners %}
<option value="{{ partner.id }}" {% if patient.partner_id == partner.id %}selected{% endif %}>{{ partner.partner_name }}</option>
{% endfor %}
</select>
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Doctor</label>
<input type="text" id="doctor" name="doctor" value="{{ patient.doctor or '' }}"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Skin Colour</label>
<select id="skin_colour" name="skin_colour"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<option value="">Select...</option>
<option value="white" {% if patient.skin_colour == 'white' %}selected{% endif %}>White</option>
<option value="black" {% if patient.skin_colour == 'black' %}selected{% endif %}>Black</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Agent Name</label>
<input type="text" id="agent_name" name="agent_name" value="{{ patient.agent_name or '' }}"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="flex items-center">
<input type="checkbox" id="is_outlab" name="is_outlab" value="true" {% if patient.is_outlab %}checked{% endif %}
class="w-4 h-4 text-indigo-600 border-slate-300 rounded focus:ring-indigo-500">
<label for="is_outlab" class="ml-2 text-sm text-slate-700">Is Outlab</label>
</div>
</div>
</div>
</div>
<!-- Tests & Packages -->
<div>
<h4 class="text-md font-semibold text-slate-700 mb-4">Tests & Packages</h4>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Select Test</label>
<select id="test_select" placeholder="Search tests..." class="w-full border border-slate-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
<option value="">Select Test...</option>
{% for test in tests %}
<option value="{{ test.id }}" data-price="{{ test.price }}">{{ test.test_name }}</option>
{% endfor %}
</select>
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Select Package</label>
<select id="package_select" placeholder="Search packages..." class="w-full border border-slate-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
<option value="">Select Package...</option>
{% for package in packages %}
<option value="{{ package.id }}" data-price="{{ package.price }}" data-name="{{ package.package_name }}">{{ package.package_name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-slate-200">
<thead class="bg-slate-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">No.</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Name</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Type</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Price</th>
<th class="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Action</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-slate-200" id="selectedItemsTable"></tbody>
</table>
<p id="emptyTableMessage" class="text-center text-slate-500 py-8">No tests or packages selected</p>
</div>
</div>
{% if has_button('patient_edit', 'discount') %}
<!-- Discount Section -->
<div class="flex justify-end">
<button type="button" onclick="toggleDiscount()" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium">💰 Discount</button>
</div>
<div id="discountSection" class="hidden grid grid-cols-1 md:grid-cols-4 gap-4 p-4 bg-green-50 rounded-lg border border-green-200">
<div>
<label class="block text-sm font-medium text-green-700 mb-1">Discount Percentage (%)</label>
<!-- ✅ REMOVED step attribute to prevent validation error -->
<input type="number" id="discount_percentage" value="0" min="0" max="100" step="any" onchange="calculateDiscount()"
class="w-full border border-green-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500">
</div>
<div>
<label class="block text-sm font-medium text-green-700 mb-1">Discount Amount</label>
<!-- ✅ REMOVED step attribute to prevent validation error -->
<input type="text" id="discount_amount_display" value="0" min="0" onchange="calculateDiscountFromAmount()"
class="w-full border border-green-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500">
</div>
<!-- ✅ Discount Note Field - Required when discount applied -->
<div class="md:col-span-2">
<label class="block text-sm font-medium text-green-700 mb-1">Discount Note <span class="text-red-500">*</span></label>
<input type="text" id="discount_note" name="discount_note" placeholder="Required when discount applied"
class="w-full border border-green-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-green-500">
</div>
</div>
{% endif %}
<!-- Payment Summary -->
<div class="grid grid-cols-1 md:grid-cols-5 gap-4 p-4 bg-slate-50 rounded-lg border border-slate-200">
<div>
<label class="block text-xs font-medium text-slate-500 mb-1">Total Price</label>
<input type="text" id="total_price" readonly class="w-full border border-slate-300 rounded-lg px-3 py-2 bg-slate-100 font-semibold">
</div>
<div>
<label class="block text-xs font-medium text-slate-500 mb-1">Total After Discount</label>
<input type="text" id="total_after_discount" readonly class="w-full border border-slate-300 rounded-lg px-3 py-2 bg-slate-100 font-semibold text-green-600">
</div>
<div>
<label class="relative flex items-center text-xs font-medium text-amber-600 mb-1 h-4">
<span>Total After Tax</span>
<label class="absolute left-1/2 -translate-x-1/2 inline-flex items-center cursor-pointer" title="Toggle Tax">
<input type="checkbox" id="apply_tax_toggle" name="apply_tax_toggle" class="sr-only peer" onchange="calculateTotalAfterDiscount()">
<div class="w-7 h-4 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-amber-500"></div>
</label>
</label>
<input type="text" id="total_after_tax" readonly class="w-full border border-amber-300 rounded-lg px-3 py-2 bg-amber-50 font-semibold text-amber-700">
</div>
<div>
<label class="block text-xs font-medium text-slate-500 mb-1">Received Amount</label>
<input type="number" id="received_amount" name="received_amount" step="0.01" oninput="calculateRemaining()" class="w-full border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500">
</div>
<div>
<label class="block text-xs font-medium text-slate-500 mb-1">Remaining Amount</label>
<input type="text" id="remaining_amount" readonly class="w-full border border-slate-300 rounded-lg px-3 py-2 bg-slate-100 font-semibold">
</div>
</div>
<!-- PAYMENT HISTORY SUMMARY -->
{% if payments %}
<div class="grid grid-cols-1 gap-4 p-4 mt-4 bg-white rounded-lg border border-slate-200 shadow-sm">
<div class="flex justify-between items-center mb-3">
<h3 class="text-sm font-semibold text-slate-800 flex items-center">
<svg class="w-4 h-4 mr-2 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
Payment History
</h3>
<button type="button" onclick="showAddPaymentModal()" class="text-xs font-semibold px-3 py-1 bg-indigo-50 text-indigo-600 rounded hover:bg-indigo-100 flex items-center transition-colors">
<svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
Add Payment
</button>
</div>
<div class="overflow-x-auto text-sm">
<table class="w-full text-left border-collapse">
<thead>
<tr class="bg-slate-50 text-slate-500 text-xs uppercase border-y border-slate-200">
<th class="py-2 px-3">Date</th>
<th class="py-2 px-3">Type</th>
<th class="py-2 px-3">Method</th>
<th class="py-2 px-3">Amount</th>
<th class="py-2 px-3">Note</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100">
{% for p in payments %}
<tr>
<td class="py-2 px-3 text-slate-600">{{ p.payment_date.strftime('%Y-%m-%d %H:%M') }}</td>
<td class="py-2 px-3 font-medium {% if p.is_refund %}text-rose-600{% else %}text-emerald-600{% endif %}">
{% if p.is_refund %}Refund{% else %}Payment{% endif %}
</td>
<td class="py-2 px-3 uppercase text-xs tracking-wider text-slate-500">{{ p.payment_method }}</td>
<td class="py-2 px-3 font-semibold {% if p.is_refund %}text-rose-600{% else %}text-emerald-600{% endif %}">
{% if p.is_refund %}-{% endif %}{{ "%.2f"|format(p.amount) }}
</td>
<td class="py-2 px-3 text-slate-500 truncate max-w-[150px]">{{ p.note or '-' }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
<!-- Hidden inputs for form submission -->
<input type="hidden" id="selected_items" name="selected_items" value="">
<input type="hidden" id="deleted_items_hidden" name="deleted_items" value="[]">
<input type="hidden" id="discount_percentage_hidden" name="discount_percentage" value="">
<input type="hidden" id="discount_amount_hidden" name="discount_amount" value="">
<!-- Save Button -->
<div class="flex justify-end pt-4 border-t border-slate-200">
<a href="/patients" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-6 py-3 rounded-lg text-sm font-medium mr-3">Cancel</a>
<button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white px-8 py-3 rounded-lg text-sm font-medium">💾 Save Changes</button>
</div>
</div>
</form>
</div>
<!-- ADD PAYMENT MODAL -->
<div id="addPaymentModal" class="fixed inset-0 z-50 hidden overflow-y-auto bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all">
<div class="flex items-center justify-between p-5 border-b border-slate-100 bg-slate-50/50">
<h3 class="text-lg font-semibold text-slate-800">Record New Payment</h3>
<button type="button" onclick="closeAddPaymentModal()" class="text-slate-400 hover:bg-slate-200 hover:text-slate-600 rounded-lg p-1.5 transition-colors">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
</button>
</div>
<form action="/patient/{{ patient.patient_id }}/payment" method="POST" class="p-5">
<input type="hidden" name="visit_id" value="{{ latest_visit.id }}">
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Amount</label>
<input type="number" name="amount" step="0.01" required value="{{ latest_visit.remaining_amount }}" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-800 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Payment Method</label>
<select name="payment_method" class="w-full border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-slate-700">
<option value="cash">💵 Cash</option>
<option value="card">💳 Card</option>
<option value="transfer">🏦 Bank Transfer</option>
<option value="insurance">🏥 Insurance</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Type</label>
<select name="is_refund" class="w-full border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-slate-700">
<option value="False">Income (Payment)</option>
<option value="True">Outcome (Refund)</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">Note (Optional)</label>
<input type="text" name="note" placeholder="e.g. installment 2" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-800 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
</div>
</div>
<div class="mt-6 flex gap-3 justify-end">
<button type="button" onclick="closeAddPaymentModal()" class="px-5 py-2 text-sm font-medium text-slate-600 bg-slate-100 rounded-lg hover:bg-slate-200 transition-colors">Cancel</button>
<button type="submit" class="px-5 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-colors shadow-sm">Save Payment</button>
</div>
</form>
</div>
</div>
<!-- Delete Test Reason Modal -->
<div id="deleteTestModal" class="fixed inset-0 z-[100] hidden items-center justify-center bg-black/50 backdrop-blur-sm">
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4 overflow-hidden transform transition-all duration-300 scale-95 opacity-0" id="deleteTestModalContent">
<div class="bg-red-50 px-6 py-4 border-b border-red-100">
<h3 class="text-lg font-semibold text-red-800 flex items-center gap-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
</svg>
Remove Existing Test
</h3>
<p class="text-sm text-red-600 mt-1">Item: <strong id="deleteTestName"></strong></p>
<p id="testResultWarning" class="hidden mt-3 p-3 rounded-lg text-sm font-semibold bg-yellow-100 text-yellow-800 outline outline-1 outline-yellow-300"></p>
</div>
<div class="px-6 py-5">
<label class="block text-sm font-medium text-slate-700 mb-2">Removal Reason <span class="text-red-500">*</span></label>
<textarea id="deleteTestReasonInput" rows="3" required
oninput="document.getElementById('deleteTestConfirmBtn').disabled = !this.value.trim();"
class="w-full border border-slate-300 rounded-lg px-3 py-2 text-slate-800 focus:ring-2 focus:ring-red-500 focus:border-red-500 focus:outline-none resize-none"
placeholder="Please enter the reason..."></textarea>
<p class="text-xs text-slate-500 mt-2">This reason will be recorded for audit purposes.</p>
</div>
<div class="px-6 py-4 bg-slate-50 flex justify-end gap-3 border-t border-slate-200">
<button type="button" onclick="closeDeleteTestModal()"
class="px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-lg hover:bg-slate-50 transition">
Cancel
</button>
<button type="button" id="deleteTestConfirmBtn" onclick="confirmDeleteTest()"
class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition disabled:opacity-50 disabled:cursor-not-allowed" disabled>
Confirm Remove
</button>
</div>
</div>
</div>
<!-- Hidden element to store orders JSON data -->
<div id="orders_json_data" style="display: none;">{{ orders_json | safe }}</div>
<!-- Tom Select JS -->
<script src="/static/vendor/tom-select/tom-select.complete.min.js"></script>
<script>
// ============================================
// ✅ COMPLETE JAVASCRIPT FOR PATIENT EDIT PAGE
// ============================================
// Global Variables
let testSelect, packageSelect;
let selectedItems = [];
let deletedItems = [];
let itemCounter = 0;
let labTaxPercentage = 0; // ✅ Tax percentage from lab info
// Format price with comma separator
function formatPrice(amount) {
return Math.round(amount).toLocaleString('en-US');
}
// Show popup notification
function showPopup(message, type = 'success') {
const container = document.getElementById('popupContainer');
if (!container) {
alert(message);
return;
}
const popup = document.createElement('div');
popup.className = `popup-notification popup-${type}`;
popup.innerHTML = `<span>${message}</span>`;
container.appendChild(popup);
setTimeout(() => {
popup.style.animation = 'slideIn 0.3s ease-out reverse';
setTimeout(() => popup.remove(), 300);
}, 3000);
}
// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
console.log('🔍 Page loaded, initializing...');
// ✅ Load existing orders from server - IMPROVED ERROR HANDLING
const ordersJsonElement = document.getElementById('orders_json_data');
let ordersJsonString = '[]';
if (ordersJsonElement) {
ordersJsonString = ordersJsonElement.textContent.trim();
}
console.log('📦 Raw orders JSON:', ordersJsonString);
try {
// ✅ Handle empty/null/invalid JSON gracefully
let ordersJson = [];
if (ordersJsonString && ordersJsonString !== 'null' && ordersJsonString.trim() !== '') {
ordersJson = JSON.parse(ordersJsonString);
}
console.log('📦 Parsed orders:', ordersJson);
if (ordersJson && Array.isArray(ordersJson) && ordersJson.length > 0) {
ordersJson.forEach((order, index) => {
console.log('➕ Adding order:', order);
addItem({
id: order.id,
name: order.name,
type: order.type || 'test',
price: parseFloat(order.price) || 0,
package_name: order.package_name,
status: order.status,
is_existing: true
});
});
calculateTotal();
document.getElementById('emptyTableMessage').style.display = 'none';
showPopup(`Loaded ${ordersJson.length} existing test(s)`, 'success');
} else {
console.log('ℹ️ No existing orders found for this patient (this is normal for new patients)');
}
} catch (e) {
console.error('❌ Error parsing orders JSON:', e);
console.error('Raw JSON:', ordersJsonString);
// Don't show error popup for empty orders - it's normal
if (ordersJsonString && ordersJsonString.trim() !== '' && ordersJsonString !== 'null') {
showPopup('⚠️ Could not load existing orders', 'error');
}
}
// Set payment values from latest visit
{% if latest_visit %}
const receivedEl = document.getElementById('received_amount');
const discountEl = document.getElementById('discount_amount_display');
const discountPctEl = document.getElementById('discount_percentage');
const discountNoteEl = document.getElementById('discount_note');
if (receivedEl) receivedEl.value = {{ latest_visit.received_amount }};
if (discountEl) discountEl.value = formatPrice(Math.round({{ latest_visit.discount_amount }}));
if (discountPctEl) discountPctEl.value = {{ latest_visit.discount_percentage|default(0) }};
if (discountNoteEl) discountNoteEl.value = "{{ latest_visit.discount_note|default('', true)|e }}";
// Populate hidden fields too
document.getElementById('discount_percentage_hidden').value = {{ latest_visit.discount_percentage|default(0) }};
document.getElementById('discount_amount_hidden').value = Math.round({{ latest_visit.discount_amount }});
const taxToggle = document.getElementById('apply_tax_toggle');
if (taxToggle) {
taxToggle.checked = {% if latest_visit.tax_applied != False %}true{% else %}false{% endif %};
}
// Auto-show discount section if discount was applied
if ({{ latest_visit.discount_amount }} > 0 || {{ latest_visit.discount_percentage|default(0) }} > 0) {
const discountSection = document.getElementById('discountSection');
if (discountSection) {
discountSection.classList.remove('hidden');
}
}
{% endif %}
// Initialize Tom Select
initializeTomSelect();
// Show success/error messages from URL
const urlParams = new URLSearchParams(window.location.search);
const success = urlParams.get('success');
const error = urlParams.get('error');
if (success) {
showPopup(success, 'success');
window.history.replaceState({}, document.title, window.location.pathname);
}
if (error) {
showPopup(decodeURIComponent(error), 'error');
window.history.replaceState({}, document.title, window.location.pathname);
}
});
// Initialize Tom Select for tests and packages
function initializeTomSelect() {
const testSelectEl = document.getElementById('test_select');
const packageSelectEl = document.getElementById('package_select');
if (!testSelectEl || !packageSelectEl) {
console.error('❌ Tom Select elements not found!');
return;
}
testSelect = new TomSelect('#test_select', {
plugins: ['dropdown_input'],
placeholder: 'Search tests...',
create: false,
maxItems: 1,
onChange: function(value) {
if (value) {
addTest(value);
testSelect.clear();
}
}
});
packageSelect = new TomSelect('#package_select', {
plugins: ['dropdown_input'],
placeholder: 'Search packages...',
create: false,
maxItems: 1,
onChange: function(value) {
if (value) {
addPackage(value);
packageSelect.clear();
}
}
});
console.log('✅ Tom Select initialized');
}
// Add test to selected items
function addTest(testId) {
const option = document.querySelector(`#test_select option[value="${testId}"]`);
if (!option) return;
const testAlreadySelected = selectedItems.some(item =>
item.type === 'test' && item.id === parseInt(testId)
);
if (testAlreadySelected) {
showPopup('This test is already selected!', 'error');
return;
}
addItem({
id: parseInt(testId),
name: option.textContent,
type: 'test',
price: parseFloat(option.dataset.price)
});
}
// Add package to selected items
function addPackage(packageId) {
const option = document.querySelector(`#package_select option[value="${packageId}"]`);
if (!option) return;
const packageAlreadySelected = selectedItems.some(item =>
item.type === 'package' && item.id === parseInt(packageId)
);
if (packageAlreadySelected) {
showPopup('This package is already selected!', 'error');
return;
}
addItem({
id: parseInt(packageId),
name: option.dataset.name || option.textContent,
type: 'package',
price: parseFloat(option.dataset.price)
});
}
// Add item to selected items array
function addItem(item) {
itemCounter++;
item.no = itemCounter;
selectedItems.push(item);
renderSelectedItems();
calculateTotal();
document.getElementById('emptyTableMessage').style.display = 'none';
}
// Remove item from selected items logic
let pendingRemoveIndex = null;
function removeItem(index) {
const item = selectedItems[index];
if (item.is_existing) {
pendingRemoveIndex = index;
document.getElementById('deleteTestName').textContent = item.name;
document.getElementById('deleteTestReasonInput').value = '';
document.getElementById('deleteTestConfirmBtn').disabled = true;
// Show result warning if test is resulted
const warningEl = document.getElementById('testResultWarning');
if (warningEl) {
warningEl.classList.add('hidden');
if (item.status && ['resulted', 'received', 'authorized', 'double_authorized'].includes(item.status.toLowerCase())) {
warningEl.textContent = `⚠️ WARNING: This test has a result (${item.status}). Removing it will discard clinical data.`;
warningEl.classList.remove('hidden');
}
}
const modal = document.getElementById('deleteTestModal');
const content = document.getElementById('deleteTestModalContent');
modal.classList.remove('hidden');
modal.classList.add('flex');
setTimeout(() => {
content.classList.remove('scale-95', 'opacity-0');
content.classList.add('scale-100', 'opacity-100');
document.getElementById('deleteTestReasonInput').focus();
}, 10);
return;
}
executeRemove(index);
}
function closeDeleteTestModal() {
const modal = document.getElementById('deleteTestModal');
const content = document.getElementById('deleteTestModalContent');
content.classList.remove('scale-100', 'opacity-100');
content.classList.add('scale-95', 'opacity-0');
setTimeout(() => {
modal.classList.add('hidden');
modal.classList.remove('flex');
pendingRemoveIndex = null;
}, 300);
}
function confirmDeleteTest() {
if (pendingRemoveIndex === null) return;
const reason = document.getElementById('deleteTestReasonInput').value.trim();
if (!reason) return;
const item = selectedItems[pendingRemoveIndex];
const confirmBtn = document.getElementById('deleteTestConfirmBtn');
// Only call API for existing tests (already in database)
if (item.is_existing) {
confirmBtn.disabled = true;
confirmBtn.textContent = 'Removing...';
const patientId = '{{ patient.patient_id }}';
const url = `/api/patients/${patientId}/remove-test?test_id=${item.id}&visit_id=${encodeURIComponent('{{ latest_visit.visit_id }}')}&reason=${encodeURIComponent(reason)}`;
fetch(url, { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.success) {
showPopup('✅ Test removed successfully', 'success');
executeRemove(pendingRemoveIndex);
closeDeleteTestModal();
} else {
showPopup('❌ Failed to remove test: ' + (data.error || 'Unknown error'), 'error');
confirmBtn.disabled = false;
confirmBtn.textContent = 'Confirm Remove';
}
})
.catch(error => {
showPopup('❌ Error: ' + error.message, 'error');
confirmBtn.disabled = false;
confirmBtn.textContent = 'Confirm Remove';
});
} else {
// New test (not yet saved) — just remove from UI
executeRemove(pendingRemoveIndex);
closeDeleteTestModal();
}
}
function executeRemove(index) {
selectedItems.splice(index, 1);
selectedItems.forEach((item, idx) => {
item.no = idx + 1;
});
itemCounter = selectedItems.length;
renderSelectedItems();
calculateTotal();
if (selectedItems.length === 0) {
document.getElementById('emptyTableMessage').style.display = 'block';
}
}
// Render selected items table
function renderSelectedItems() {
const tbody = document.getElementById('selectedItemsTable');
if (!tbody) return;
if (selectedItems.length === 0) {
tbody.innerHTML = '';
document.getElementById('selected_items').value = '[]';
return;
}
tbody.innerHTML = selectedItems.map((item, index) => `
<tr class="hover:bg-slate-50">
<td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">${item.no}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-slate-800">${item.name}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm">
<span class="px-2 py-1 rounded-full text-xs ${item.type === 'test' ? 'bg-blue-100 text-blue-800' : 'bg-purple-100 text-purple-800'}">
${item.type === 'test' ? 'Test' : 'Package'}
</span>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">${formatPrice(item.price)}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
<button type="button" onclick="removeItem(${index})" class="text-red-600 hover:text-red-900">🗑️ Remove</button>
</td>
</tr>
`).join('');
document.getElementById('selected_items').value = JSON.stringify(selectedItems);
}
// Toggle discount section
function toggleDiscount() {
const section = document.getElementById('discountSection');
section.classList.toggle('hidden');
}
// Toggle More Information section
function toggleMoreInfo() {
const section = document.getElementById('moreInfoSection');
const icon = document.getElementById('moreIcon');
section.classList.toggle('hidden');
icon.classList.toggle('rotate-180');
}
// Calculate discount from percentage
function calculateDiscount() {
const percentage = parseFloat(document.getElementById('discount_percentage').value) || 0;
const totalPrice = parseFloat(document.getElementById('total_price').value.replace(/,/g, '')) || 0;
const discountAmount = (totalPrice * percentage) / 100;
document.getElementById('discount_amount_display').value = formatPrice(discountAmount);
document.getElementById('discount_percentage_hidden').value = percentage;
document.getElementById('discount_amount_hidden').value = Math.round(discountAmount);
calculateTotalAfterDiscount();
}
// Calculate discount from amount
function calculateDiscountFromAmount() {
const amount = parseFloat(document.getElementById('discount_amount_display').value.replace(/,/g, '')) || 0;
const totalPrice = parseFloat(document.getElementById('total_price').value.replace(/,/g, '')) || 0;
const percentage = totalPrice > 0 ? (amount / totalPrice) * 100 : 0;
document.getElementById('discount_percentage').value = percentage;
document.getElementById('discount_percentage_hidden').value = percentage;
document.getElementById('discount_amount_hidden').value = amount;
calculateTotalAfterDiscount();
}
// Calculate total price
function calculateTotal() {
const total = selectedItems.reduce((sum, item) => sum + item.price, 0);
const totalEl = document.getElementById('total_price');
if (totalEl) {
totalEl.value = formatPrice(total);
}
calculateTotalAfterDiscount();
}
// Calculate total after discount
function calculateTotalAfterDiscount() {
const totalEl = document.getElementById('total_price');
const receivedEl = document.getElementById('received_amount');
const remainingEl = document.getElementById('remaining_amount');
const totalAfterDiscountEl = document.getElementById('total_after_discount');
const totalAfterTaxEl = document.getElementById('total_after_tax');
if (!totalEl || !receivedEl || !remainingEl || !totalAfterDiscountEl) return;
const total = parseFloat(totalEl.value.replace(/,/g, '')) || 0;
// Safely get discount amount
const discountEl = document.getElementById('discount_amount_display');
const discount = discountEl ? (parseFloat(discountEl.value.replace(/,/g, '')) || 0) : 0;
const afterDiscount = total - discount;
totalAfterDiscountEl.value = formatPrice(afterDiscount);
// ✅ Calculate Total After Tax
const applyTax = document.getElementById('apply_tax_toggle') ? document.getElementById('apply_tax_toggle').checked : false;
const taxAmount = applyTax ? (labTaxPercentage / 100) * afterDiscount : 0;
const afterTax = afterDiscount + taxAmount;
if (totalAfterTaxEl) totalAfterTaxEl.value = formatPrice(afterTax);
calculateRemaining();
}
// Calculate remaining amount
function calculateRemaining() {
const afterTaxEl = document.getElementById('total_after_tax');
const receivedEl = document.getElementById('received_amount');
const remainingEl = document.getElementById('remaining_amount');
if (!afterTaxEl || !receivedEl || !remainingEl) return;
const afterTax = parseFloat(afterTaxEl.value.replace(/,/g, '')) || 0;
const received = parseFloat(receivedEl.value.replace(/,/g, '')) || 0;
const remaining = afterTax - received;
remainingEl.value = formatPrice(remaining);
}
// Detect manual changes to received amount
document.addEventListener('DOMContentLoaded', function() {
// ✅ Load lab info for tax percentage
fetch('/api/lab-info')
.then(response => response.json())
.then(data => {
if (data.success && data.lab_info) {
labTaxPercentage = parseFloat(data.lab_info.tax_percentage) || 0;
console.log('✅ Tax percentage loaded:', labTaxPercentage + '%');
// Recalculate with tax now that we have the percentage
calculateTotalAfterDiscount();
}
})
.catch(error => console.error('Error loading lab info:', error));
});
// ✅ Arabic Name Gender Detection - PATTERN ONLY (Most Efficient!)
function detectNameGender(name) {
if (!name || name.trim().length === 0) return null;
const cleanName = name.trim();
const lastChar = cleanName.slice(-1);
const lastTwoChars = cleanName.slice(-2);
// ✅ Female patterns (Arabic characters)
if (lastChar === 'ة' || lastChar === 'ه') return 'female';
if (lastTwoChars === 'ية' || lastTwoChars === 'اء') return 'female';
// ✅ Default: assume male
return 'male';
}
// ✅ Verify Gender vs Name
function verifyGender() {
const nameInput = document.getElementById('full_name');
const genderSelect = document.getElementById('gender');
const warningEl = document.getElementById('genderWarning');
// Only verify on the first name before the first space
const name = nameInput.value.trim().split(' ')[0];
const selectedGender = genderSelect.value;
// ✅ Only verify if both name and gender are filled
if (!name || !selectedGender) {
if (warningEl) warningEl.classList.add('hidden');
return;
}
// ✅ Detect gender from name patterns
const detectedGender = detectNameGender(name);
// ✅ Show warning if mismatch
if (detectedGender && detectedGender !== selectedGender) {
if (warningEl) warningEl.classList.remove('hidden');
} else {
if (warningEl) warningEl.classList.add('hidden');
}
}
// Calculate age from date of birth
function calculateAge() {
const dobInput = document.getElementById('date_of_birth').value;
const ageEl = document.getElementById('age');
const ageUnitEl = document.getElementById('age_unit');
if (!dobInput) {
ageEl.value = '';
ageUnitEl.value = 'year';
return;
}
const dob = new Date(dobInput);
const today = new Date();
let age = today.getFullYear() - dob.getFullYear();
const monthDiff = today.getMonth() - dob.getMonth();
const dayDiff = today.getDate() - dob.getDate();
let ageUnit = 'year';
if (age < 1) {
if (monthDiff < 1 || (monthDiff === 0 && dayDiff < 0)) {
age = today.getMonth() * 30 + today.getDate() - (dob.getMonth() * 30 + dob.getDate());
ageUnit = 'day';
if (age > 30) {
age = Math.floor(age / 30);
ageUnit = 'month';
}
} else {
age = monthDiff;
ageUnit = 'month';
}
}
ageEl.value = age;
ageUnitEl.value = ageUnit;
}
// Load regions based on province
function loadRegions() {
const provinceId = document.getElementById('province_id');
const regionSelect = document.getElementById('region_id');
if (!provinceId || !regionSelect) return;
if (!provinceId.value) {
regionSelect.disabled = true;
regionSelect.innerHTML = '<option value="">Select Region...</option>';
return;
}
fetch('/api/regions?province_id=' + provinceId.value)
.then(response => response.json())
.then(regions => {
regionSelect.innerHTML = '<option value="">Select Region...</option>';
regions.forEach(region => {
const option = document.createElement('option');
option.value = region.id;
option.textContent = region.region_name;
regionSelect.appendChild(option);
});
regionSelect.disabled = false;
});
}
// Print Receipt Function - Opens proper receipt page
async function printReceipt(patientId) {
window.open('/print-receipt/' + patientId, '_blank');
}
// Print Barcode Function - Opens proper barcode page
async function printBarcode(patientId) {
window.open('/print-barcode/' + patientId, '_blank');
}
// Form submission validation
document.addEventListener('DOMContentLoaded', function() {
const editForm = document.getElementById('editForm');
if (editForm) {
editForm.addEventListener('submit', function(e) {
// ✅ DEBUG: Ensure hidden fields are synced right before submit
document.getElementById('selected_items').value = JSON.stringify(selectedItems);
document.getElementById('deleted_items_hidden').value = JSON.stringify(deletedItems);
console.log('📤 FORM SUBMIT - selectedItems:', JSON.stringify(selectedItems));
console.log('📤 FORM SUBMIT - deletedItems:', JSON.stringify(deletedItems));
console.log('📤 FORM SUBMIT - hidden selected_items value:', document.getElementById('selected_items').value);
console.log('📤 FORM SUBMIT - hidden deleted_items value:', document.getElementById('deleted_items_hidden').value);
const discountAmount = parseFloat(document.getElementById('discount_amount_hidden').value) || 0;
const discountPercentage = parseFloat(document.getElementById('discount_percentage_hidden').value) || 0;
const discountNote = document.getElementById('discount_note').value.trim();
if (discountAmount > 0 || discountPercentage > 0) {
if (!discountNote) {
e.preventDefault();
showPopup('⚠️ Discount note is required when applying discount', 'error');
document.getElementById('discount_note').focus();
return;
}
}
if (selectedItems.length === 0) {
e.preventDefault();
showPopup('⚠️ Please add at least one test or package', 'error');
}
});
}
});
</script>
<script src="/static/vendor/bwip-js/bwip-js.min.js"></script>
<script src="/static/vendor/bwip-js/barcode-helper.js"></script>
{% endblock %}
<!-- templates/patient_edit.html -->
{% extends "base.html" %}
{% block title %}Edit Patient - NexLab{% endblock %}
{% block page_title %}Edit Patient Data{% endblock %}
{% block content %}
<!-- Tom Select CSS -->
<link href="/static/vendor/tom-select/tom-select.css" rel="stylesheet">
<style>
.popup-notification {
position: fixed;
top: 20px;
right: 20px;
padding: 16px 24px;
border-radius: 8px;
color: white;
font-weight: 500;
z-index: 9999;
animation: slideIn 0.3s ease-out;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.popup-success { background: #10b981; }
.popup-error { background: #ef4444; }
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.ts-wrapper { position: relative ; width: 100%; z-index: 100; }
.ts-dropdown {
max-height: 250px ;
overflow-y: auto ;
z-index: 9999 ;
position: absolute ;
width: 100% ;
}
</style>
<!-- Popup Container -->
<div id="popupContainer"></div>
<div class="bg-white rounded-xl shadow-sm border border-slate-200">
<!-- Header -->
<div class="p-6 border-b border-slate-200">
<div class="flex items-center justify-between flex-wrap gap-4">
<div>
<h3 class="text-lg font-semibold text-slate-800">Edit Patient</h3>
<p class="text-sm text-slate-500">Patient ID: <strong class="font-mono">{{ patient.patient_id }}</strong></p>
</div>
<div class="flex gap-3">
<a href="/patients" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-lg text-sm font-medium">← Back</a>
<button type="button" onclick="printReceipt('{{ patient.patient_id }}')" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg text-sm font-medium">📄 Print Receipt</button>
<button type="button" onclick="printBarcode('{{ patient.patient_id }}')" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium">🏷️ Print Barcode</button>
</div>
</div>
</div>
<form method="POST" action="/patients/update/{{ patient.patient_id }}?visit_id={{ latest_visit.visit_id }}" id="editForm">
<div class="p-6 space-y-6">
<!-- Main Information -->
<div>
<h4 class="text-md font-semibold text-slate-700 mb-4">Main Information</h4>
<div class="flex flex-wrap items-start gap-x-4 gap-y-4">
<div class="w-full sm:w-24">
<label class="block text-sm font-medium text-slate-700 mb-1">Patient ID</label>
<input type="text" value="{{ patient.patient_id }}" readonly
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 bg-slate-100 font-mono focus:outline-none">
</div>
<div class="w-full sm:min-w-[16rem] flex-1 relative">
<label class="block text-sm font-medium text-slate-700 mb-1">Patient Name *</label>
<input type="text" id="full_name" name="full_name" value="{{ patient.full_name }}" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<!-- ✅ Gender Warning Message -->
<div id="genderWarning" class="hidden absolute top-full left-0 mt-1 w-full z-10 p-3 bg-green-50 border border-green-200 rounded-lg shadow-md flex items-center">
<span class="mr-2 text-lg">ℹ️</span>
<span class="font-medium text-sm text-green-800">تنبيه: الجنس قد لا يتطابق مع الاسم المدخل</span>
</div>
</div>
<div class="w-full sm:w-40">
<label class="block text-sm font-medium text-slate-700 mb-1">Gender *</label>
<select id="gender" name="gender" required onchange="verifyGender(); this.className = this.options[this.selectedIndex].className + ' w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none';"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none {{ 'text-blue-600 bg-blue-50 font-medium' if patient.gender == 'male' else 'text-pink-600 bg-pink-50 font-medium' }}">
<option value="">Select...</option>
<option value="male" class="text-blue-600 bg-blue-50 font-medium" {% if patient.gender == 'male' %}selected{% endif %}>Male</option>
<option value="female" class="text-pink-600 bg-pink-50 font-medium" {% if patient.gender == 'female' %}selected{% endif %}>Female</option>
</select>
</div>
<div class="w-full sm:w-24">
<label class="block text-sm font-medium text-slate-700 mb-1">Age *</label>
<input type="number" id="age" name="age" value="{{ patient.age }}" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="w-full sm:w-40">
<label class="block text-sm font-medium text-slate-700 mb-1">Date of Birth</label>
<input type="date" id="date_of_birth" name="date_of_birth" value="{{ patient.date_of_birth.strftime('%Y-%m-%d') if patient.date_of_birth else '' }}" onchange="calculateAge()"
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
</div>
<div class="w-full sm:w-32">
<label class="block text-sm font-medium text-slate-700 mb-1">Age Unit *</label>
<select id="age_unit" name="age_unit" required
class="w-full h-11 border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500 focus:outline-none">
<option value="year" {% if patient.age_unit == 'year' %}selected{% endif %}>Years</option>