NexLab_System / templates /print_report.html
alisaleem97's picture
Upload folder using huggingface_hub
6ea020b verified
Raw History Blame Contribute Delete
21.7 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Print Report - {{ patient.patient_id }}</title>
<link href="/static/vendor/fonts/fonts.css" rel="stylesheet">
<link
href="/static/vendor/fonts/fonts.css"
rel="stylesheet">
<link href="/static/tailwind.min.css" rel="stylesheet">
<link href="/static/vendor/font-awesome/css/all.min.css" rel="stylesheet">
<style>
/* LOAD YOUR CUSTOM ARABIC FONT */
@font-face {
font-family: 'FormaDJRArabic';
src: url('/uploads/alfont_com_FormaDJRArabicDeck-Bold-Testing.otf') format('opentype');
font-weight: normal;
font-style: normal;
}
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
background: #e2e8f0;
display: flex;
justify-content: center;
font-family: 'FormaDJRArabic', 'Inter', sans-serif;
}
.report-canvas {
background: white;
position: relative;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
margin: 20px auto;
overflow: hidden;
/* width and min-height set via inline style */
}
.design-element {
position: absolute;
word-wrap: break-word;
overflow: hidden;
min-width: 20px;
min-height: 10px;
}
@page {
size: {{ template.paper_width if template and template.paper_width else '210mm' }} {{ template.paper_height if template and template.paper_height else '297mm' }};
margin: 0;
}
@media print {
html, body {
background: white !important;
margin: 0 !important;
padding: 0 !important;
display: block;
}
.report-canvas {
box-shadow: none !important;
border: none !important;
margin: 0 !important;
page-break-after: always;
overflow: visible !important;
}
.no-print {
display: none !important;
}
}
</style>
</head>
<body>
<div class="no-print fixed top-4 right-4 flex gap-2 z-50">
<button onclick="handlePrint()"
class="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-2 rounded-lg font-bold shadow-lg transition">
<i class="fas fa-print mr-2"></i> Print Report
</button>
<button onclick="window.close()"
class="bg-slate-600 hover:bg-slate-700 text-white px-4 py-2 rounded-lg font-bold shadow-lg transition">
Close
</button>
</div>
<div id="pagesContainer" class="flex flex-col items-center w-full"></div>
<script>
// Safely convert Python dictionaries into JavaScript Objects
const rawTemplate = {{ template | default ({}) | tojson | safe }};
const patient = {{ patient | default ({}) | tojson | safe }};
const visit = {{ visit | default ({}) | tojson | safe }};
const labInfo = {{ lab_info | default ({}) | tojson | safe }};
const barcodeData = "{{ barcode_data | default('') }}";
let testResults = {{ results | default ([]) | tojson | safe }};
let designElements = [];
let paperWidth = "{{ template.paper_width if template and template.paper_width else '210mm' }}";
let paperHeight = "{{ template.paper_height if template and template.paper_height else '297mm' }}";
try {
console.log("Parsing template data...");
let parsed = typeof rawTemplate === 'string' ? JSON.parse(rawTemplate) : rawTemplate;
// Handle cases where the database double-nested the JSON string
if (parsed.elements && typeof parsed.elements === 'string') {
parsed = JSON.parse(parsed.elements);
}
designElements = parsed.elements || [];
if (parsed.paperWidth) paperWidth = parsed.paperWidth;
if (parsed.paperHeight) paperHeight = parsed.paperHeight;
console.log(`Loaded ${designElements.length} elements.`);
} catch (e) {
console.error("Template parse error:", e);
}
// The canvas creation logic has been moved to renderCanvas to support multiple pages
function formatDate(dateStr) {
if (!dateStr) return '';
const d = new Date(dateStr);
return isNaN(d) ? dateStr : d.toISOString().split('T')[0];
}
async function handlePrint() {
if (visit && visit.visit_id) {
try {
await fetch(`/api/mark-printed/${visit.visit_id}`, { method: 'POST' });
} catch(e) {
console.error("Failed to mark as printed", e);
}
}
window.print();
}
async function fetchResultsAndRender() {
try {
console.log("Fetching results from API...");
const urlParams = new URLSearchParams(window.location.search);
const orderIds = urlParams.get('order_ids');
const queryVisitId = urlParams.get('visit_id') || (visit ? visit.visit_id : null);
let apiUrl = `/api/double-authorized-tests/${patient.patient_id}?`;
if (orderIds) apiUrl += `order_ids=${orderIds}&`;
if (queryVisitId) apiUrl += `visit_id=${queryVisitId}&`;
const response = await fetch(apiUrl);
const data = await response.json();
if (data.success) testResults = data.results || [];
} catch (e) {
console.error("Failed to fetch results:", e);
}
renderCanvas();
}
function renderCanvas() {
console.log("Drawing canvas elements...");
const container = document.getElementById('pagesContainer');
container.innerHTML = '';
// Group the tests based on print_separately
let groups = [];
let currentGroup = [];
let isSeparateGroup = false;
testResults.forEach(row => {
if (row.type === 'parent' || row.type === 'standalone') {
if (row.print_separately) {
if (currentGroup.length > 0) {
groups.push(currentGroup);
currentGroup = [];
}
groups.push([row]);
isSeparateGroup = true;
} else {
if (isSeparateGroup) {
isSeparateGroup = false;
}
currentGroup.push(row);
}
} else if (row.type === 'child') {
if (isSeparateGroup) {
groups[groups.length - 1].push(row);
} else {
currentGroup.push(row);
}
}
});
if (currentGroup.length > 0) groups.push(currentGroup);
if (groups.length === 0) {
// If there are no results, still render one blank template page
groups = [[]];
}
groups.forEach((groupResults) => {
const canvas = document.createElement('div');
canvas.className = `report-canvas`;
canvas.style.width = paperWidth;
canvas.style.minHeight = paperHeight;
designElements.forEach(el => {
const div = document.createElement('div');
div.className = 'design-element';
div.style.left = el.x + 'px';
div.style.top = el.y + 'px';
div.style.width = el.width + 'px';
if (el.type === 'result_table') {
div.style.height = 'auto';
div.style.overflow = 'visible';
} else {
div.style.height = el.height + 'px';
}
div.style.fontSize = el.fontSize + 'px';
div.style.fontWeight = el.fontWeight || 'normal';
div.style.fontFamily = el.fontFamily || "'FormaDJRArabic', sans-serif";
div.style.textAlign = el.align || 'left';
div.style.color = el.color || '#0f172a';
div.style.zIndex = el.zIndex || 10;
div.style.opacity = el.opacity || 1.0;
div.innerHTML = `<div style="width:100%; height:100%;">${getElementHtml(el, groupResults)}</div>`;
canvas.appendChild(div);
});
container.appendChild(canvas);
});
console.log("Drawing complete!");
}
function getElementHtml(el, groupResults) {
const labelHtml = el.label ? `<span style="font-weight: 600; margin-right: 6px; opacity: 0.8;">${el.label}</span>` : '';
if (el.type === 'patient_name') return `${labelHtml}<span>${patient.full_name || ''}</span>`;
if (el.type === 'patient_id') return `${labelHtml}<span>${patient.patient_id || ''}</span>`;
if (el.type === 'patient_age') {
const ageUnit = patient.age_unit ? (patient.age_unit === 'day' ? 'day' : patient.age_unit.charAt(0).toUpperCase()) : '';
return `${labelHtml}<span>${patient.age || '-'} ${ageUnit} / ${patient.gender ? patient.gender.toUpperCase() : ''}</span>`;
}
if (el.type === 'patient_fasting_time') return `${labelHtml}<span>${patient.fasting_time != null ? patient.fasting_time + ' hr' : 'N/A'}</span>`;
if (el.type === 'visit_id') return `${labelHtml}<span>${visit ? visit.visit_id : ''}</span>`;
if (el.type === 'visit_date') return `${labelHtml}<span>${visit ? formatDate(visit.visit_date) : formatDate(patient.created_at)}</span>`;
if (el.type === 'doctor_name') return `${labelHtml}<span>${patient.doctor || ''}</span>`;
if (el.type === 'agent_name') return `${labelHtml}<span>${patient.agent_name || ''}</span>`;
if (el.type === 'lab_name') return `<div style="font-weight:${el.fontWeight || 'bold'};">${labInfo.lab_name || ''}</div>`;
if (el.type === 'lab_title') return `${labelHtml}<span>${labInfo.lab_title || ''}</span>`;
if (el.type === 'lab_address') return `${labelHtml}<span>${labInfo.lab_address || ''}</span>`;
if (el.type === 'lab_phone_1') return `${labelHtml}<span>${labInfo.lab_phone_1 || ''}</span>`;
if (el.type === 'lab_phone_2') return `${labelHtml}<span>${labInfo.lab_phone_2 || ''}</span>`;
if (el.type === 'lab_email') return `${labelHtml}<span>${labInfo.lab_email || ''}</span>`;
if (el.type === 'lab_website') return `${labelHtml}<span>${labInfo.lab_website || ''}</span>`;
if (el.type === 'lab_currency') return `${labelHtml}<span>${labInfo.lab_currency || ''}</span>`;
if (el.type === 'first_doctor_name') return `${labelHtml}<div style="white-space: pre-wrap; display: inline-block; vertical-align: top;">${labInfo.first_doctor_name || ''}</div>`;
if (el.type === 'second_doctor_name') return `${labelHtml}<div style="white-space: pre-wrap; display: inline-block; vertical-align: top;">${labInfo.second_doctor_name || ''}</div>`;
if (el.type === 'lab_note_1') return `${labelHtml}<span style="white-space: pre-wrap;">${labInfo.lab_note_1 || ''}</span>`;
if (el.type === 'lab_note_2') return `${labelHtml}<span style="white-space: pre-wrap;">${labInfo.lab_note_2 || ''}</span>`;
if (['lab_logo', 'lab_stamp_1', 'lab_stamp_2', 'lab_signature_1', 'lab_signature_2', 'lab_image_1', 'lab_image_2', 'lab_qr_1', 'lab_qr_2'].includes(el.type)) {
const imgVal = labInfo[el.type];
if (imgVal) return `<img src="/uploads/${imgVal}" style="width:100%; height:100%; object-fit:contain;">`;
return '';
}
if (el.type === 'barcode_image') {
return `<div class="bg-white p-1 w-full h-full flex flex-col items-center justify-center">
<img src="data:image/png;base64,${barcodeData}" style="max-width:100%; max-height:80%; object-fit:contain; display:block;">
<span style="font-size:10px; font-family:monospace; margin-top:2px; display:block;">${patient.patient_id}</span>
</div>`;
}
if (el.type === 'shape_line') return `<div style="width:100%; height:100%; background-color:${el.color || el.borderColor || '#334155'};"></div>`;
if (el.type === 'custom_text') return el.content || '';
if (el.type === 'watermark') {
if (el.image) return `<div style="width:100%; height:100%; background-image:url('/uploads/${el.image}'); background-size:contain; background-repeat:no-repeat; background-position:center;"></div>`;
return '';
}
if (el.type === 'result_table') return buildResultTable(el, groupResults);
return '';
}
function buildResultTable(el, groupResults) {
const cols = (el.columns || ['test', 'result', 'flag', 'range', 'unit']).filter(c => c.trim() !== '');
if (cols.length === 0) return '';
// Generate a unique scope ID for this table instance
const scopeId = 'rt_' + Math.random().toString(36).substr(2, 6);
const bWidth = el.borderWidth !== undefined ? el.borderWidth : 1;
const hAlign = el.headerAlign || 'left';
const rAlign = el.rowAlign || 'left';
const hHeight = el.headerHeight > 0 ? el.headerHeight + 'px' : 'auto';
const rHeight = el.rowHeight > 0 ? el.rowHeight + 'px' : 'auto';
// Build a scoped <style> block — guaranteed to override any inherited or default styles
let scopeStyle = `<style>
.${scopeId} { width: 100%; border-collapse: collapse; table-layout: ${el.tableLayout || 'auto'}; }
.${scopeId} th {
padding: ${el.cellPadding !== undefined ? el.cellPadding : 8}px;
border: ${bWidth}px solid ${el.borderColor || '#e2e8f0'};
white-space: pre-wrap; word-break: break-word; vertical-align: middle;
background: ${el.headerBg || '#f8fafc'};
color: ${el.headerColor || '#1e293b'};
font-size: ${el.headerFontSize || 12}px;
font-weight: bold;
text-align: ${hAlign} !important;
height: ${hHeight};
}
.${scopeId} td {
padding: ${el.cellPadding !== undefined ? el.cellPadding : 8}px;
border: ${bWidth}px solid ${el.borderColor || '#e2e8f0'};
white-space: pre-wrap; word-break: break-word; vertical-align: middle;
font-size: ${el.rowFontSize || 12}px;
color: ${el.rowTextColor || '#334155'};
text-align: ${rAlign} !important;
height: ${rHeight};
}
.${scopeId} .zebra-row { background-color: ${el.zebraColor || '#f8fafc'}; }
.${scopeId} .parent-row td { font-weight: 700; background: rgba(0,0,0,0.04); color: #000; }
</style>`;
let colGroupHtml = '';
if (el.tableLayout === 'fixed' && el.colWidths) {
const widths = el.colWidths.split(',').map(s => s.trim());
colGroupHtml = '<colgroup>' + widths.map(w => `<col style="width: ${w};">`).join('') + '</colgroup>';
}
const headers = { test: 'Test Name', result: 'Result', flag: 'Flag', range: 'Ref. Range', unit: 'Unit' };
let html = scopeStyle;
if (groupResults.length === 0) {
html += `<table class="${scopeId}">${colGroupHtml}`;
html += `<thead><tr>`;
cols.forEach(c => { html += `<th>${headers[c.toLowerCase()] || c.toUpperCase()}</th>`; });
html += `</tr></thead><tbody>`;
html += `<tr><td colspan="${cols.length}" style="text-align:center !important;">No results found</td></tr>`;
html += `</tbody></table>`;
} else {
let pendingRemark = null;
let tableOpen = false;
const reopenTable = () => {
if (!tableOpen) {
html += `<table class="${scopeId}">${colGroupHtml}`;
html += `<thead><tr>`;
cols.forEach(c => { html += `<th>${headers[c.toLowerCase()] || c.toUpperCase()}</th>`; });
html += `</tr></thead><tbody>`;
tableOpen = true;
}
};
const closeTable = () => {
if (tableOpen) {
html += `</tbody></table>`;
tableOpen = false;
}
};
const flushRemark = (isEnd = false) => {
if (pendingRemark) {
closeTable();
html += `<div style="width: 100%; border: ${bWidth}px solid ${el.borderColor || '#e2e8f0'}; padding: 10px; margin-top: 5px; margin-bottom: 5px; text-align: center; color: darkred; font-weight: bold; background: #fff; box-sizing: border-box;">
${pendingRemark}
</div>`;
pendingRemark = null;
}
};
groupResults.forEach((row, index) => {
if (row.type === 'parent' || row.type === 'standalone') {
flushRemark();
let cleanNote = row.note ? row.note.replace(/(<([^>]+)>)/gi, "").trim() : '';
if (cleanNote !== '' || (row.note && row.note.includes('<img'))) {
pendingRemark = row.note;
}
}
if (row.result_type === 'paragraph' && row.type !== 'parent') {
closeTable();
const title = row.type === 'child' ? row.parameter_name : row.test_name;
html += `<div style="text-align: left; font-weight: bold; margin-top: 15px; margin-bottom: 5px; font-size: ${el.headerFontSize || 14}px; color: ${el.headerColor || '#1e293b'};">
${title}
</div>`;
html += `<div style="margin-bottom: 15px; text-align: left; box-sizing: border-box; background: transparent; color: ${el.rowTextColor || '#334155'};">
${row.result_value || ''}
</div>`;
return;
}
reopenTable();
let zebraClass = (el.zebraStripes && index % 2 !== 0) ? 'zebra-row' : '';
let parentClass = (row.type === 'parent') ? 'parent-row' : '';
html += `<tr class="${zebraClass} ${parentClass}">`;
if (row.type === 'parent') {
html += `<td colspan="${cols.length}">${row.test_name}</td>`;
} else {
cols.forEach(c => {
let val = '';
let styleAdd = '';
if (c === 'test') {
val = row.type === 'child' ? `<span style="padding-left: 15px;">${row.parameter_name}</span>` : row.test_name;
} else if (c === 'result') {
val = row.result_value || '-';
if (row.flag && row.flag !== 'N') {
styleAdd = 'font-weight: bold; color: #dc2626;';
}
} else if (c === 'flag') { val = row.flag || ''; }
else if (c === 'range') { val = row.range || ''; }
else if (c === 'unit') { val = row.unit || ''; }
html += `<td style="${styleAdd}">${val}</td>`;
});
}
html += `</tr>`;
});
flushRemark(true);
closeTable();
}
return html;
}
// --- EXECUTE IMMEDIATELY (No window.onload) ---
console.log("Executing script...");
renderCanvas();
// If we are missing results (because we are in the web view), fetch them now
if (testResults.length === 0 && patient && patient.patient_id) {
fetchResultsAndRender();
}
</script>
</body>
</html>