feat: sistema de observação por voz - fase 1

- FAB flutuante para gravar observação
- Modal com timer + waveform animado
- Botão sair para desistir
- MediaRecorder API (webm/opus)
- Transcrição via OpenAI Whisper
- Relatório estruturado via GPT
- Salva em .md com frontmatter (data/hora/timestamp)
- Índice JSON para consulta posterior
- Rotas: transcrever, salvar, listar observações
- multer para upload de áudio
This commit is contained in:
2026-05-27 15:46:03 +00:00
parent d309b03b55
commit ea8e33c891
72 changed files with 8531 additions and 4 deletions
+177
View File
@@ -1968,6 +1968,183 @@ const initApp = () => {
// Inicializar reconhecimento de voz
initVoiceRecognition();
// ============================================================
// SISTEMA DE OBSERVAÇÃO POR VOZ
// ============================================================
const recordModal = document.getElementById('recordModal');
const fabRecord = document.getElementById('fabRecord');
const btnExitRecord = document.getElementById('btnExitRecord');
const btnStopRecord = document.getElementById('btnStopRecord');
const recordStateRecording = document.getElementById('recordStateRecording');
const recordStateProcessing = document.getElementById('recordStateProcessing');
const recordStatePreview = document.getElementById('recordStatePreview');
const recordTimer = document.getElementById('recordTimer');
const reportContent = document.getElementById('reportContent');
const previewDateTime = document.getElementById('previewDateTime');
const btnDiscardReport = document.getElementById('btnDiscardReport');
const btnSaveReport = document.getElementById('btnSaveReport');
let mediaRecorder = null;
let audioChunks = [];
let recordingStartTime = null;
let timerInterval = null;
let generatedReport = null;
// Abrir modal e iniciar gravação
if (fabRecord) {
fabRecord.addEventListener('click', async () => {
audioChunks = [];
generatedReport = null;
// Mostra estado inicial (gravando)
recordStateRecording.style.display = 'flex';
recordStateProcessing.style.display = 'none';
recordStatePreview.style.display = 'none';
recordModal.style.display = 'flex';
// Inicia timer
recordingStartTime = Date.now();
timerInterval = setInterval(updateTimer, 1000);
updateTimer();
// Solicita permissão e inicia gravação
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm;codecs=opus' });
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) audioChunks.push(e.data);
};
mediaRecorder.start(100); // chunk a cada 100ms
} catch (err) {
console.error('Erro ao acessar microfone:', err);
alert('Não foi possível acessar o microfone. Verifique as permissões.');
closeRecordModal();
}
});
}
// Atualizar timer
const updateTimer = () => {
if (!recordingStartTime) return;
const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
const mins = Math.floor(elapsed / 60).toString().padStart(2, '0');
const secs = (elapsed % 60).toString().padStart(2, '0');
recordTimer.textContent = `${mins}:${secs}`;
};
// Parar gravação e processar
if (btnStopRecord) {
btnStopRecord.addEventListener('click', async () => {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
mediaRecorder.stream.getTracks().forEach(t => t.stop());
}
clearInterval(timerInterval);
// Mostra processando
recordStateRecording.style.display = 'none';
recordStateProcessing.style.display = 'flex';
// Envia áudio para servidor
const blob = new Blob(audioChunks, { type: 'audio/webm' });
const formData = new FormData();
formData.append('audio', blob, 'recording.webm');
try {
const res = await fetch('/api/observacao/transcrever', {
method: 'POST',
body: formData
});
const data = await res.json();
generatedReport = data.report;
showReportPreview(data);
} catch (err) {
console.error('Erro ao processar observação:', err);
alert('Erro ao processar sua observação. Tente novamente.');
closeRecordModal();
}
});
}
// Mostrar prévia do relatório
const showReportPreview = (data) => {
recordStateProcessing.style.display = 'none';
recordStatePreview.style.display = 'flex';
const now = new Date();
previewDateTime.textContent = now.toLocaleString('pt-BR', {
day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit'
});
reportContent.innerHTML = marked.parse(generatedReport || 'Relatório não disponível.');
reportContent.querySelectorAll('pre code').forEach(b => hljs.highlightElement(b));
};
// Descartar relatório
if (btnDiscardReport) {
btnDiscardReport.addEventListener('click', () => {
generatedReport = null;
closeRecordModal();
});
}
// Salvar relatório
if (btnSaveReport) {
btnSaveReport.addEventListener('click', async () => {
if (!generatedReport) return;
btnSaveReport.disabled = true;
btnSaveReport.textContent = 'Salvando...';
try {
const res = await fetch('/api/observacao/salvar', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ report: generatedReport })
});
const data = await res.json();
if (data.success) {
alert('Relatório salvo com sucesso!');
} else {
alert('Erro ao salvar: ' + (data.error || 'desconhecido'));
}
} catch (err) {
console.error('Erro ao salvar:', err);
alert('Erro ao salvar o relatório.');
} finally {
btnSaveReport.disabled = false;
btnSaveReport.textContent = 'Salvar';
closeRecordModal();
}
});
}
// Sair / descartar
if (btnExitRecord) {
btnExitRecord.addEventListener('click', closeRecordModal);
}
// Fechar modal
const closeRecordModal = () => {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
mediaRecorder.stream.getTracks().forEach(t => t.stop());
}
clearInterval(timerInterval);
audioChunks = [];
generatedReport = null;
recordModal.style.display = 'none';
};
// Fechar clicando fora
if (recordModal) {
recordModal.addEventListener('click', (e) => {
if (e.target === recordModal) closeRecordModal();
});
}
};
// Player de áudio personalizado global para as mídias geradas
+63 -2
View File
@@ -102,8 +102,15 @@
</div>
</aside>
<!-- Overlay para fechar sidebar clicando fora no mobile -->
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<!-- FAB: Nova Observação por Voz -->
<button class="fab-record" id="fabRecord" title="Nova Observação (gravar)">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 18.75a6 6 0 0 0 6-6v-1.5m-6 7.5a6 6 0 0 1-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z" />
</svg>
</button>
<!-- Overlay para fechar sidebar clicando fora no mobile -->
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<!-- Área principal do Chat -->
<main class="chat-area">
@@ -247,6 +254,60 @@
</main>
</div>
<!-- Modal de Gravação de Observação -->
<div id="recordModal" class="settings-modal" style="display: none;">
<div class="settings-modal-content record-modal-content">
<div class="record-modal-header">
<button id="btnExitRecord" class="btn-exit-record" title="Sair e descartar">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
<span>Sair</span>
</button>
<h3>🎤 Nova Observação</h3>
<div style="width: 60px;"></div>
</div>
<div class="record-modal-body">
<!-- Estado: gravando -->
<div id="recordStateRecording" class="record-state" style="display: none;">
<div class="record-timer" id="recordTimer">00:00</div>
<div class="record-waveform" id="recordWaveform">
<div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div>
<div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div>
<div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div>
<div class="wave-bar"></div><div class="wave-bar"></div><div class="wave-bar"></div>
</div>
<p class="record-hint">Fale livremente sobre a observação...</p>
<button id="btnStopRecord" class="btn-stop-record">
<div class="stop-icon"></div>
<span>Parar</span>
</button>
</div>
<!-- Estado: processando -->
<div id="recordStateProcessing" class="record-state" style="display: none;">
<div class="record-spinner"></div>
<p>Analisando sua observação...</p>
<small style="color: var(--text-muted);">Transcrevendo e gerando relatório</small>
</div>
<!-- Estado: prévia -->
<div id="recordStatePreview" class="record-state" style="display: none;">
<div class="preview-header">
<h4>📋 Relatório Gerado</h4>
<span id="previewDateTime"></span>
</div>
<div id="reportContent" class="report-content"></div>
<div class="preview-actions">
<button id="btnDiscardReport" class="btn-discard">Descartar</button>
<button id="btnSaveReport" class="btn-save-report">Salvar</button>
</div>
</div>
</div>
</div>
</div>
<!-- Modal de Configurações do Agente -->
<div id="settingsModal" class="settings-modal" style="display: none;">
<div class="settings-modal-content settings-modal-large">
+272
View File
@@ -2533,6 +2533,278 @@ code {
color: #ef4444;
}
/* FAB: Floating Action Button para gravação */
.fab-record {
position: fixed;
bottom: 24px;
right: 24px;
width: 60px;
height: 60px;
border-radius: 50%;
background: var(--brand-green, #10a37f);
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 20px rgba(16, 163, 127, 0.4);
transition: all 0.3s;
z-index: 998;
color: white;
}
.fab-record svg {
width: 28px;
height: 28px;
}
.fab-record:hover {
transform: scale(1.08);
box-shadow: 0 6px 24px rgba(16, 163, 127, 0.5);
}
.fab-record:active {
transform: scale(0.95);
}
/* Modal de Gravação */
.record-modal-content {
max-width: 480px !important;
border-radius: 20px !important;
overflow: hidden;
}
.record-modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid var(--border-light, #262626);
background: var(--bg-secondary, #1a1a1a);
}
.record-modal-header h3 {
margin: 0;
font-size: 1.1rem;
color: var(--text-primary, #ffffff);
font-family: 'Outfit', sans-serif;
}
.btn-exit-record {
display: flex;
align-items: center;
gap: 6px;
background: transparent;
border: 1px solid var(--border-light, #262626);
color: var(--text-secondary, #a3a3a3);
padding: 8px 14px;
border-radius: 8px;
font-size: 0.85rem;
cursor: pointer;
transition: all 0.2s;
}
.btn-exit-record:hover {
color: #ef4444;
border-color: #ef4444;
}
.btn-exit-record svg {
width: 16px;
height: 16px;
}
.record-modal-body {
padding: 30px 20px;
min-height: 320px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.record-state {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
}
/* Timer */
.record-timer {
font-size: 3rem;
font-weight: 700;
color: var(--brand-green, #10a37f);
font-family: 'Inter', sans-serif;
letter-spacing: 2px;
}
/* Waveform */
.record-waveform {
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
height: 60px;
}
.wave-bar {
width: 4px;
background: var(--brand-green, #10a37f);
border-radius: 2px;
animation: wave 1s ease-in-out infinite;
opacity: 0.7;
}
.wave-bar:nth-child(1) { animation-delay: 0s; height: 20px; }
.wave-bar:nth-child(2) { animation-delay: 0.1s; height: 35px; }
.wave-bar:nth-child(3) { animation-delay: 0.2s; height: 50px; }
.wave-bar:nth-child(4) { animation-delay: 0.3s; height: 40px; }
.wave-bar:nth-child(5) { animation-delay: 0.4s; height: 55px; }
.wave-bar:nth-child(6) { animation-delay: 0.5s; height: 30px; }
.wave-bar:nth-child(7) { animation-delay: 0.6s; height: 45px; }
.wave-bar:nth-child(8) { animation-delay: 0.7s; height: 25px; }
.wave-bar:nth-child(9) { animation-delay: 0.8s; height: 50px; }
.wave-bar:nth-child(10) { animation-delay: 0.9s; height: 35px; }
.wave-bar:nth-child(11) { animation-delay: 1.0s; height: 20px; }
.wave-bar:nth-child(12) { animation-delay: 1.1s; height: 40px; }
@keyframes wave {
0%, 100% { transform: scaleY(1); }
50% { transform: scaleY(0.5); }
}
.record-hint {
color: var(--text-secondary, #a3a3a3);
font-size: 0.95rem;
text-align: center;
}
.btn-stop-record {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
background: #ef4444;
border: none;
color: white;
padding: 20px 36px;
border-radius: 50%;
cursor: pointer;
transition: all 0.2s;
margin-top: 10px;
}
.btn-stop-record:hover {
background: #dc2626;
transform: scale(1.05);
}
.stop-icon {
width: 24px;
height: 24px;
background: white;
border-radius: 4px;
}
.btn-stop-record span {
font-size: 0.85rem;
font-weight: 500;
}
/* Spinner */
.record-spinner {
width: 60px;
height: 60px;
border: 4px solid var(--border-light, #262626);
border-top-color: var(--brand-green, #10a37f);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Prévia do relatório */
.preview-header {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.preview-header h4 {
margin: 0;
color: var(--text-primary, #ffffff);
font-size: 1rem;
}
#previewDateTime {
font-size: 0.75rem;
color: var(--text-muted, #666);
}
.report-content {
width: 100%;
max-height: 300px;
overflow-y: auto;
background: var(--bg-secondary, #1a1a1a);
border: 1px solid var(--border-light, #262626);
border-radius: 12px;
padding: 16px;
font-size: 0.9rem;
color: var(--text-primary, #ffffff);
line-height: 1.6;
}
.report-content p { margin: 0 0 8px 0; }
.report-content strong { color: var(--brand-green, #10a37f); }
.preview-actions {
width: 100%;
display: flex;
gap: 12px;
margin-top: 16px;
}
.btn-discard {
flex: 1;
padding: 12px;
background: transparent;
border: 1px solid var(--border-light, #262626);
color: var(--text-secondary, #a3a3a3);
border-radius: 10px;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.2s;
}
.btn-discard:hover {
border-color: #ef4444;
color: #ef4444;
}
.btn-save-report {
flex: 1;
padding: 12px;
background: var(--brand-green, #10a37f);
border: none;
color: white;
border-radius: 10px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.btn-save-report:hover {
opacity: 0.9;
}
/* Animação fadeIn global */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }