pediatric-ai-scribe-v3/public/js/soap.js
Daniel 09193538fb v6.2: Session management, password change, audit logging, refine context, UI fixes
Security:
- Add session management: users can view/revoke active sessions in Settings
- Add password change in Settings (requires current password, HIBP check)
- Force logout all sessions on password reset
- Fix logout to destroy server-side session (was only clearing cookie)
- Add trust proxy for correct client IP in rate limiting and audit logs
- Add CORS support for multiple domains (CORS_ORIGINS env var)
- Add HIBP breach check endpoint and inline warnings on password fields

Audit logging:
- Add audit logging to all 24 PHI-handling endpoints across 13 route files
- Covers: generation, transcription, TTS, refine, encounters, documents, Nextcloud
- All fire-and-forget (no response delay)

AI improvements:
- Refine now includes original source material (transcript, notes, labs)
  so AI can reference the full input when modifying output
- Add correction tracking (trackAIOutput) to sick visit and well visit tabs
- Fix sickvisit missing from encounter save noteIdMap

UI fixes:
- Non-blocking busy bar for transcription and AI generation (replaces full-screen overlay)
- Fix encounter recording: hide record button during recording (was showing two stop buttons)
- Fix ROS/PE "All WNL" stacking duplicate event handlers; add Clear buttons
- Enlarge AI instructions textarea in Learning Hub CMS

Domain:
- Primary domain now app.pedshub.com, with scribe.pedshub.com and peds.danvics.com as CORS origins
2026-04-08 20:27:45 +02:00

164 lines
6.8 KiB
JavaScript

(function() {
var _inited = false;
document.addEventListener('tabChanged', function(e) {
if (e.detail.tab !== 'soap' || _inited) return;
_inited = true;
var recordBtn = document.getElementById('soap-record-btn');
var indicator = document.getElementById('soap-recording-indicator');
var timerEl = document.getElementById('soap-timer');
var transcript = document.getElementById('soap-transcript');
var clearBtn = document.getElementById('soap-clear');
var generateBtn = document.getElementById('soap-generate-btn');
var outputCard = document.getElementById('soap-output');
var soapText = document.getElementById('soap-text');
var modelTag = document.getElementById('soap-model-tag');
var recorder = new AudioRecorder();
recorder._module = 'soap';
var timer = createTimer(timerEl);
var isRecording = false;
var recognition = createSpeechRecognition();
var finalText = '';
var sessionFinals = '';
function escHtml(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
if (recognition) {
recognition.onresult = function(e) {
var interim = '';
for (var i = e.resultIndex; i < e.results.length; i++) {
if (e.results[i].isFinal) {
var chunk = e.results[i][0].transcript + ' ';
var deduped = deduplicateFinal(chunk, finalText + sessionFinals);
sessionFinals += deduped;
} else {
interim = e.results[i][0].transcript;
}
}
var combined = finalText + sessionFinals;
transcript.innerHTML = escHtml(combined) + (interim ? '<span style="color:#9ca3af;">' + escHtml(interim) + '</span>' : '');
};
recognition.onend = function() {
finalText += sessionFinals;
sessionFinals = '';
if (isRecording) try { recognition.start(); } catch(e) {}
};
}
recordBtn.addEventListener('click', function() {
if (!isRecording) {
finalText = '';
sessionFinals = '';
recorder.start().then(function() {
isRecording = true;
recordBtn.classList.add('recording');
recordBtn.querySelector('span').textContent = 'Stop';
indicator.classList.remove('hidden');
timer.start();
if (recognition) try { recognition.start(); } catch(e) {}
}).catch(function() { showToast('Microphone denied', 'error'); });
} else {
isRecording = false;
var dur = timer.stop();
recordBtn.classList.remove('recording');
recordBtn.querySelector('span').textContent = 'Dictate';
indicator.classList.add('hidden');
if (recognition) try { recognition.stop(); } catch(e) {}
var liveText = (finalText + sessionFinals).trim();
if (window._transcribeAvailable === false) {
recorder.stop().then(function() {});
if (liveText) transcript.textContent = liveText;
showToast('Using browser speech recognition', 'info');
} else {
showBusy('Transcribing...');
recorder.stop().then(function(blob) {
if (!blob) { hideBusy(); if (liveText) transcript.textContent = liveText; return; }
if (blob.size > 24 * 1024 * 1024) {
hideBusy();
transcript.textContent = liveText;
showToast('Recording too large for AI transcription — using live transcript', 'info');
return;
}
return transcribeAudio(blob).then(function(data) {
hideBusy();
if (data.success) transcript.textContent = data.text;
else if (data.noProvider) { if (liveText) transcript.textContent = liveText; showToast('Using live transcript', 'info'); }
else { if (liveText) transcript.textContent = liveText; showToast(data.error || 'Transcription failed — using live transcript', 'error'); }
});
}).catch(function(err) { hideBusy(); if (liveText) transcript.textContent = liveText; showToast('Transcription error: ' + (err.message || 'unknown'), 'error'); });
}
}
});
clearBtn.addEventListener('click', function() {
transcript.textContent = ''; finalText = ''; outputCard.classList.add('hidden');
var instrEl = document.getElementById('soap-instructions');
if (instrEl) instrEl.value = '';
window._savedEncId_soap = null;
var labelEl = document.getElementById('soap-label');
if (labelEl) labelEl.value = '';
});
generateBtn.addEventListener('click', function() {
var text = transcript.innerText.trim();
if (!text) { showToast('No input', 'error'); return; }
showBusy('Generating SOAP note...');
var memoriesPromise = (typeof getUserMemoryContext === 'function') ? getUserMemoryContext() : Promise.resolve('');
memoriesPromise.then(function(memCtx) {
return fetch('/api/generate-soap', {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
transcript: text,
patientAge: document.getElementById('soap-age').value,
patientGender: document.getElementById('soap-gender').value,
type: document.getElementById('soap-type').value,
additionalInstructions: document.getElementById('soap-instructions').value,
physicianMemories: memCtx || null,
model: getSelectedModel()
})
});
})
.then(function(r) { return r.json(); })
.then(function(data) {
hideBusy();
if (data.success) {
setOutputText(soapText, data.soap);
storeSourceContext('soap-text', transcript.innerText.trim());
if (typeof trackAIOutput === 'function') trackAIOutput('soap-text', data.soap);
modelTag.textContent = (data.model || '').split('/').pop();
outputCard.classList.remove('hidden');
outputCard.scrollIntoView({ behavior: 'smooth' });
showToast('SOAP note generated!', 'success');
} else showToast(data.error || 'Failed', 'error');
})
.catch(function(err) { hideBusy(); showToast(err.message, 'error'); });
});
document.getElementById('soap-refine-btn').addEventListener('click', function() { refineDocument('soap-text', 'soap-refine-input'); });
document.getElementById('soap-shorten-btn').addEventListener('click', function() { shortenDocument('soap-text'); });
// Register load handler for resuming saved SOAP notes
if (typeof registerEncounterLoadHandler === 'function') {
registerEncounterLoadHandler('soap', function(enc) {
if (enc.transcript) transcript.textContent = enc.transcript;
if (enc.generated_note) {
setOutputText(soapText, enc.generated_note);
outputCard.classList.remove('hidden');
}
try {
var pd = JSON.parse(enc.partial_data || '{}');
if (pd.age) document.getElementById('soap-age').value = pd.age;
if (pd.gender) document.getElementById('soap-gender').value = pd.gender;
if (pd.type) document.getElementById('soap-type').value = pd.type;
} catch(e) {}
});
}
console.log('✅ SOAP module loaded');
});
})();