feat: soporte multi-archivo en modal Agendar Domicilio
This commit is contained in:
+113
-105
@@ -6589,30 +6589,13 @@ if (!isUserLoggedIn()) {
|
||||
<!-- ── FORMULARIO ── -->
|
||||
<div id="labdom-form-panel" class="modal-body pb-2">
|
||||
|
||||
<!-- Orden médica (adjunta / agregar / cambiar) -->
|
||||
<!-- Órdenes médicas (múltiples archivos permitidos) -->
|
||||
<div class="mb-3">
|
||||
<div id="labdom-img-prev" class="d-flex align-items-center gap-3 p-2 bg-light rounded border" style="display:none">
|
||||
<div id="labdom-file-thumb" class="flex-shrink-0">
|
||||
<img id="labdom-img-el" src="" class="rounded border" style="max-height:80px;max-width:110px;object-fit:cover">
|
||||
<div id="labdom-file-icon" class="rounded border bg-white text-center" style="width:80px;height:80px;display:none;align-items:center;justify-content:center"></div>
|
||||
</div>
|
||||
<div class="flex-grow-1 overflow-hidden">
|
||||
<p class="mb-1 fw-semibold small text-secondary"><i class="fas fa-paperclip me-1"></i>Orden médica adjunta</p>
|
||||
<small id="labdom-file-name" class="text-muted d-block mb-2" style="max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"></small>
|
||||
<div class="d-flex gap-2">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary py-0 px-2" onclick="labDomicilio._cambiarOrden()" title="Cambiar archivo">
|
||||
<i class="fas fa-exchange-alt me-1"></i>Cambiar
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-danger py-0 px-2" onclick="labDomicilio._eliminarOrden()" title="Eliminar orden">
|
||||
<i class="fas fa-trash me-1"></i>Eliminar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" id="labdom-btn-add-orden" class="btn btn-sm btn-outline-primary w-100 py-1" onclick="labDomicilio._cambiarOrden()" style="display:none">
|
||||
<div id="labdom-files-list" class="d-none mb-2"></div>
|
||||
<button type="button" id="labdom-btn-add-orden" class="btn btn-sm btn-outline-primary w-100 py-1" onclick="labDomicilio._agregarArchivo()">
|
||||
<i class="fas fa-paperclip me-1"></i>Adjuntar orden médica <span class="fw-normal text-muted">(opcional)</span>
|
||||
</button>
|
||||
<input type="file" id="labdom-orden-input" accept="image/*,.pdf,.doc,.docx" style="display:none">
|
||||
<input type="file" id="labdom-orden-input" accept="image/*,.pdf,.doc,.docx" multiple style="display:none">
|
||||
</div>
|
||||
|
||||
<!-- ── TIPO (particular/seguro) — PRIMERO y llamativo ── -->
|
||||
@@ -6867,10 +6850,10 @@ if (!isUserLoggedIn()) {
|
||||
// ══════════════════════════════════════════════════════════════════════════════
|
||||
const labDomicilio = (() => {
|
||||
// Estado interno
|
||||
let _msgId = null;
|
||||
let _localFile = null;
|
||||
let _newOrderFile = null; // nuevo archivo de orden cargado desde el modal
|
||||
let _convId = null;
|
||||
let _msgId = null;
|
||||
let _localFiles = []; // string[] — nombres de archivos ya en el servidor
|
||||
let _newOrderFiles = []; // File[] — archivos nuevos pendientes de subir
|
||||
let _convId = null;
|
||||
let _pacienteId = null;
|
||||
let _isNewPaciente = false; // true = paciente nuevo (no existe en BD aún)
|
||||
let _pacNombre = '';
|
||||
@@ -6962,9 +6945,9 @@ const labDomicilio = (() => {
|
||||
|
||||
/* Abre el modal desde el botón del mensaje imagen */
|
||||
abrir(msgId, localFile, convId) {
|
||||
_msgId = msgId || null;
|
||||
_localFile = localFile|| null;
|
||||
_convId = convId ? parseInt(convId) : null;
|
||||
_msgId = msgId || null;
|
||||
_localFiles = localFile ? [localFile] : [];
|
||||
_convId = convId ? parseInt(convId) : null;
|
||||
// Guardar también el userId actual para usarContacto cuando convId no esté disponible
|
||||
if (!_convId && typeof chatApp !== 'undefined' && chatApp.currentUserId) {
|
||||
_convId = '__user:' + chatApp.currentUserId;
|
||||
@@ -6973,7 +6956,7 @@ const labDomicilio = (() => {
|
||||
mostrarFormulario();
|
||||
labDomicilio._resetFull();
|
||||
|
||||
labDomicilio._updateOrdenPreview();
|
||||
labDomicilio._renderFilesPanel();
|
||||
|
||||
if (!_bsModal) _bsModal = new bootstrap.Modal('#modalAgendarDomicilio', { backdrop: true, keyboard: true });
|
||||
_bsModal.show();
|
||||
@@ -6984,10 +6967,10 @@ const labDomicilio = (() => {
|
||||
|
||||
/* Reset completo (nombre paciente + todos los campos) */
|
||||
_resetFull() {
|
||||
_pacienteId = null;
|
||||
_pacNombre = '';
|
||||
_histDirs = [];
|
||||
_newOrderFile = null;
|
||||
_pacienteId = null;
|
||||
_pacNombre = '';
|
||||
_histDirs = [];
|
||||
_newOrderFiles = [];
|
||||
$('labdom-pac-busq').value = '';
|
||||
$('labdom-pac-list').style.display = 'none';
|
||||
$('labdom-pac-buscar').classList.remove('d-none');
|
||||
@@ -7009,71 +6992,94 @@ const labDomicilio = (() => {
|
||||
labDomicilio._resetDomicilio();
|
||||
},
|
||||
|
||||
/* Actualiza la previa de orden médica en el modal (imagen o icono de archivo) */
|
||||
_updateOrdenPreview() {
|
||||
const prevDiv = document.getElementById('labdom-img-prev');
|
||||
/* Renderiza la lista de órdenes médicas adjuntas (soporta múltiples archivos) */
|
||||
_renderFilesPanel() {
|
||||
const listDiv = document.getElementById('labdom-files-list');
|
||||
const addBtn = document.getElementById('labdom-btn-add-orden');
|
||||
const imgEl = document.getElementById('labdom-img-el');
|
||||
const iconEl = document.getElementById('labdom-file-icon');
|
||||
const nameEl = document.getElementById('labdom-file-name');
|
||||
if (!prevDiv) return;
|
||||
if (_localFile || _newOrderFile) {
|
||||
prevDiv.style.display = '';
|
||||
if (addBtn) addBtn.style.display = 'none';
|
||||
const fileName = _newOrderFile ? _newOrderFile.name : (_localFile || '');
|
||||
if (nameEl) nameEl.textContent = fileName;
|
||||
const isImage = /\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(fileName);
|
||||
if (isImage) {
|
||||
if (imgEl) {
|
||||
imgEl.style.display = '';
|
||||
if (_newOrderFile) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = ev => { imgEl.src = ev.target.result; };
|
||||
reader.readAsDataURL(_newOrderFile);
|
||||
} else {
|
||||
imgEl.src = `uploads/media/${_localFile}`;
|
||||
}
|
||||
}
|
||||
if (iconEl) iconEl.style.display = 'none';
|
||||
} else {
|
||||
if (imgEl) imgEl.style.display = 'none';
|
||||
if (iconEl) {
|
||||
const ext = (fileName || '').split('.').pop().toLowerCase();
|
||||
const iconMap = { pdf: 'fas fa-file-pdf text-danger', doc: 'fas fa-file-word text-primary', docx: 'fas fa-file-word text-primary', mp4: 'fas fa-file-video text-warning', mkv: 'fas fa-file-video text-warning', mp3: 'fas fa-file-audio text-success', ogg: 'fas fa-file-audio text-success', webm: 'fas fa-file-video text-warning' };
|
||||
iconEl.innerHTML = `<i class="${iconMap[ext] || 'fas fa-file text-secondary'}" style="font-size:2rem"></i>`;
|
||||
iconEl.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
prevDiv.style.display = 'none';
|
||||
if (addBtn) addBtn.style.display = '';
|
||||
if (!listDiv) return;
|
||||
const iconMap = { pdf: 'fas fa-file-pdf text-danger', doc: 'fas fa-file-word text-primary', docx: 'fas fa-file-word text-primary', mp4: 'fas fa-file-video text-warning', mkv: 'fas fa-file-video text-warning', mp3: 'fas fa-file-audio text-success', ogg: 'fas fa-file-audio text-success', webm: 'fas fa-file-video text-warning' };
|
||||
const total = _localFiles.length + _newOrderFiles.length;
|
||||
if (total === 0) {
|
||||
listDiv.classList.add('d-none');
|
||||
listDiv.innerHTML = '';
|
||||
if (addBtn) addBtn.innerHTML = '<i class="fas fa-paperclip me-1"></i>Adjuntar orden médica <span class="fw-normal text-muted">(opcional)</span>';
|
||||
return;
|
||||
}
|
||||
if (addBtn) addBtn.innerHTML = '<i class="fas fa-plus me-1"></i>Añadir otro archivo';
|
||||
let html = '<div class="d-flex flex-column gap-1">';
|
||||
_localFiles.forEach((fname, i) => {
|
||||
const isImg = /\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(fname);
|
||||
const ext = (fname || '').split('.').pop().toLowerCase();
|
||||
const iCls = iconMap[ext] || 'fas fa-file text-secondary';
|
||||
const thumb = isImg
|
||||
? `<img src="uploads/media/${escAtr(fname)}" class="rounded" style="height:38px;width:52px;object-fit:cover">`
|
||||
: `<i class="${iCls}" style="font-size:1.5rem"></i>`;
|
||||
html += `<div class="d-flex align-items-center gap-2 py-1 px-2 bg-light rounded border">
|
||||
<div class="flex-shrink-0 d-flex align-items-center justify-content-center" style="width:52px;height:38px">${thumb}</div>
|
||||
<small class="flex-grow-1 text-muted text-truncate" style="max-width:180px">${escLab(fname)}</small>
|
||||
<button type="button" class="btn btn-sm btn-outline-danger py-0 px-1 ms-1" onclick="labDomicilio._eliminarArchivo('local',${i})" title="Quitar"><i class="fas fa-trash-alt"></i></button>
|
||||
</div>`;
|
||||
});
|
||||
_newOrderFiles.forEach((file, i) => {
|
||||
const isImg = /^image\//.test(file.type);
|
||||
const ext = file.name.split('.').pop().toLowerCase();
|
||||
const iCls = iconMap[ext] || 'fas fa-file text-secondary';
|
||||
const tid = `labdom-nth-${i}`;
|
||||
const thumb = isImg
|
||||
? `<img id="${tid}" src="" class="rounded" style="height:38px;width:52px;object-fit:cover">`
|
||||
: `<i class="${iCls}" style="font-size:1.5rem"></i>`;
|
||||
html += `<div class="d-flex align-items-center gap-2 py-1 px-2 bg-light rounded border">
|
||||
<div class="flex-shrink-0 d-flex align-items-center justify-content-center" style="width:52px;height:38px">${thumb}</div>
|
||||
<small class="flex-grow-1 text-muted text-truncate" style="max-width:180px">${escLab(file.name)} <span class="badge bg-warning text-dark ms-1" style="font-size:.6rem">nuevo</span></small>
|
||||
<button type="button" class="btn btn-sm btn-outline-danger py-0 px-1 ms-1" onclick="labDomicilio._eliminarArchivo('new',${i})" title="Quitar"><i class="fas fa-trash-alt"></i></button>
|
||||
</div>`;
|
||||
});
|
||||
html += '</div>';
|
||||
listDiv.innerHTML = html;
|
||||
listDiv.classList.remove('d-none');
|
||||
// Cargar previsualizaciones de imágenes nuevas
|
||||
_newOrderFiles.forEach((file, i) => {
|
||||
if (/^image\//.test(file.type)) {
|
||||
const img = document.getElementById(`labdom-nth-${i}`);
|
||||
if (img) { const rd = new FileReader(); rd.onload = ev => { img.src = ev.target.result; }; rd.readAsDataURL(file); }
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/* Abre el selector de archivo para cambiar o agregar la orden médica */
|
||||
_cambiarOrden() {
|
||||
/* Abre el selector de archivo para agregar una o más órdenes médicas */
|
||||
_agregarArchivo() {
|
||||
const inp = document.getElementById('labdom-orden-input');
|
||||
if (!inp) return;
|
||||
const handler = (e) => {
|
||||
inp.removeEventListener('change', handler);
|
||||
const file = e.target.files && e.target.files[0];
|
||||
if (!file) return;
|
||||
_newOrderFile = file;
|
||||
_localFile = null;
|
||||
labDomicilio._updateOrdenPreview();
|
||||
const files = e.target.files;
|
||||
if (!files || !files.length) return;
|
||||
for (const f of files) _newOrderFiles.push(f);
|
||||
labDomicilio._renderFilesPanel();
|
||||
inp.value = '';
|
||||
};
|
||||
inp.addEventListener('change', handler);
|
||||
inp.click();
|
||||
},
|
||||
|
||||
/* Elimina la orden médica adjunta */
|
||||
/* Elimina un archivo concreto de la lista (local = del servidor, new = pendiente subir) */
|
||||
_eliminarArchivo(source, index) {
|
||||
if (source === 'local') {
|
||||
if (index === 0) _msgId = null;
|
||||
_localFiles.splice(index, 1);
|
||||
} else {
|
||||
_newOrderFiles.splice(index, 1);
|
||||
}
|
||||
labDomicilio._renderFilesPanel();
|
||||
},
|
||||
|
||||
/* Mantiene compatibilidad con código externo que llame _eliminarOrden() */
|
||||
_eliminarOrden() {
|
||||
if (!confirm('¿Eliminar la orden médica adjunta?')) return;
|
||||
_localFile = null;
|
||||
_newOrderFile = null;
|
||||
_msgId = null;
|
||||
labDomicilio._updateOrdenPreview();
|
||||
if (!confirm('¿Eliminar todas las órdenes médicas adjuntas?')) return;
|
||||
_localFiles = [];
|
||||
_newOrderFiles = [];
|
||||
_msgId = null;
|
||||
labDomicilio._renderFilesPanel();
|
||||
},
|
||||
|
||||
/* Muestra/oculta el campo «nombre del seguro» según la selección */
|
||||
@@ -7410,22 +7416,23 @@ const labDomicilio = (() => {
|
||||
notas_admin: fv('labdom-notas') || null,
|
||||
};
|
||||
|
||||
// Subir nuevo archivo de orden si el usuario cambió o agregó uno desde el modal
|
||||
if (_newOrderFile) {
|
||||
// Subir todos los archivos nuevos y añadirlos a _localFiles
|
||||
for (const file of _newOrderFiles) {
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append('file', _newOrderFile);
|
||||
fd.append('file', file);
|
||||
const upRes = await fetch('api/lab/upload_orden.php', { method: 'POST', body: fd });
|
||||
const upData = await upRes.json();
|
||||
if (upData.success && upData.local_file) {
|
||||
_localFile = upData.local_file;
|
||||
_newOrderFile = null;
|
||||
_localFiles.push(upData.local_file);
|
||||
}
|
||||
} catch (_e) { /* silencioso — no bloquea el flujo */ }
|
||||
}
|
||||
_newOrderFiles = [];
|
||||
|
||||
// Si hay orden médica (original o recién subida), crear registro y enlazar
|
||||
if (_localFile) {
|
||||
// Crear registro de orden por cada archivo y enlazarlo al domicilio
|
||||
let firstOrdenId = null;
|
||||
for (let _fi = 0; _fi < _localFiles.length; _fi++) {
|
||||
try {
|
||||
const convIdNum = (_convId && !String(_convId).startsWith('__user:'))
|
||||
? parseInt(_convId) : null;
|
||||
@@ -7434,19 +7441,20 @@ const labDomicilio = (() => {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
paciente_id: _pacienteId,
|
||||
local_file: _localFile,
|
||||
media_message_id: _msgId || null,
|
||||
local_file: _localFiles[_fi],
|
||||
media_message_id: (_fi === 0 ? _msgId : null) || null,
|
||||
conversation_id: convIdNum,
|
||||
examenes_solicitados: datos.examenes_solicitados,
|
||||
estado: 'pendiente',
|
||||
}),
|
||||
});
|
||||
const orData = await orRes.json();
|
||||
if (orData.success && orData.orden_id) {
|
||||
datos.orden_id = orData.orden_id;
|
||||
if (orData.success && orData.orden_id && firstOrdenId === null) {
|
||||
firstOrdenId = orData.orden_id;
|
||||
}
|
||||
} catch (_) { /* no bloquea si falla la creación de la orden */ }
|
||||
}
|
||||
if (firstOrdenId) datos.orden_id = firstOrdenId;
|
||||
|
||||
try {
|
||||
const r = await fetch('api/lab/save_domicilio.php', {
|
||||
@@ -7598,9 +7606,9 @@ const labDomicilio = (() => {
|
||||
pacienteId: _pacienteId,
|
||||
pacNombre: _pacNombre,
|
||||
histDirs: [..._histDirs],
|
||||
msgId: _msgId,
|
||||
localFile: _localFile,
|
||||
newOrderFile: _newOrderFile,
|
||||
msgId: _msgId,
|
||||
localFiles: [..._localFiles],
|
||||
newOrderFiles: [..._newOrderFiles],
|
||||
cardVisible: !document.getElementById('labdom-pac-card')?.classList.contains('d-none'),
|
||||
pacInfo: {
|
||||
nombre: document.getElementById('labdom-pac-nombre')?.value || '',
|
||||
@@ -7683,13 +7691,13 @@ const labDomicilio = (() => {
|
||||
labDomicilio._resetFull(); // limpia el DOM
|
||||
|
||||
// Restaurar estado interno DESPUÉS del reset (para que no se sobreescriba)
|
||||
_convId = sesion.convId;
|
||||
_pacienteId = sesion.pacienteId;
|
||||
_pacNombre = sesion.pacNombre;
|
||||
_histDirs = sesion.histDirs || [];
|
||||
_msgId = sesion.msgId;
|
||||
_localFile = sesion.localFile;
|
||||
_newOrderFile = sesion.newOrderFile || null;
|
||||
_convId = sesion.convId;
|
||||
_pacienteId = sesion.pacienteId;
|
||||
_pacNombre = sesion.pacNombre;
|
||||
_histDirs = sesion.histDirs || [];
|
||||
_msgId = sesion.msgId;
|
||||
_localFiles = sesion.localFiles || [];
|
||||
_newOrderFiles = sesion.newOrderFiles || [];
|
||||
|
||||
// Restaurar campos del formulario
|
||||
const f = sesion.fields || {};
|
||||
@@ -7734,7 +7742,7 @@ const labDomicilio = (() => {
|
||||
}
|
||||
|
||||
labDomicilio._calcTotal();
|
||||
labDomicilio._updateOrdenPreview();
|
||||
labDomicilio._renderFilesPanel();
|
||||
|
||||
// Abrir el modal
|
||||
if (!_bsModal) _bsModal = new bootstrap.Modal('#modalAgendarDomicilio', { backdrop: true, keyboard: true });
|
||||
|
||||
Reference in New Issue
Block a user