feat: perfil WhatsApp (foto, about, datos) y reset+sync de plantillas

This commit is contained in:
Lizandro Guarnizo
2026-03-13 23:50:30 -05:00
parent 290cdcc7ff
commit 7df05ee3fb
6 changed files with 715 additions and 0 deletions
+161
View File
@@ -117,6 +117,11 @@ class SimpleWhatsAppManager {
case 'templates':
this.loadTemplates();
break;
case 'whatsapp_profile':
if (typeof window.loadWhatsAppProfile === 'function') {
window.loadWhatsAppProfile();
}
break;
case 'broadcast':
// Recargar plantillas cuando se abre el tab de broadcast
if (typeof loadBroadcastTemplates === 'function') {
@@ -5098,4 +5103,160 @@ window.toggleAdminUserStatus = async function(userId, isActive) {
console.error(`Error ${action}ando usuario:`, error);
alert(`Error al ${action} usuario: ` + error.message);
}
// ─────────────────────────────────────────────────────────────────────────────
// PERFIL DE WHATSAPP BUSINESS
// ─────────────────────────────────────────────────────────────────────────────
window.loadWhatsAppProfile = async function() {
if (!window.whatsappManager) return;
window.whatsappManager.showInfo('Cargando perfil desde WhatsApp...');
try {
const res = await window.whatsappManager.apiCall('get_whatsapp_profile.php');
if (!res || !res.success) {
window.whatsappManager.showError(res?.error || 'Error al obtener el perfil');
return;
}
const p = res.data || {};
document.getElementById('wp-about').value = p.about || '';
document.getElementById('wp-description').value = p.description || '';
document.getElementById('wp-address').value = p.address || '';
document.getElementById('wp-email').value = p.email || '';
document.getElementById('wp-website').value = (p.websites && p.websites[0]) ? p.websites[0] : '';
const vertSel = document.getElementById('wp-vertical');
if (vertSel && p.vertical) {
vertSel.value = p.vertical;
}
// Foto de perfil
const img = document.getElementById('wp-profile-photo-preview');
const placeholder = document.getElementById('wp-profile-photo-placeholder');
if (p.profile_picture_url && img) {
img.src = p.profile_picture_url;
img.style.display = 'inline-block';
if (placeholder) placeholder.style.display = 'none';
}
window.whatsappManager.showSuccess('Perfil cargado correctamente');
} catch (e) {
window.whatsappManager.showError('Error: ' + e.message);
}
};
window.saveWhatsAppProfile = async function() {
if (!window.whatsappManager) return;
const payload = {
about: document.getElementById('wp-about')?.value?.trim() || '',
description: document.getElementById('wp-description')?.value?.trim() || '',
address: document.getElementById('wp-address')?.value?.trim() || '',
email: document.getElementById('wp-email')?.value?.trim() || '',
vertical: document.getElementById('wp-vertical')?.value || '',
websites: [document.getElementById('wp-website')?.value?.trim()].filter(Boolean),
};
try {
window.whatsappManager.showInfo('Guardando perfil...');
const res = await window.whatsappManager.apiCall('update_whatsapp_profile.php', {
method: 'POST',
body: payload,
});
if (res && res.success) {
window.whatsappManager.showSuccess(res.message || 'Perfil actualizado correctamente');
} else {
window.whatsappManager.showError(res?.error || 'Error al guardar el perfil');
}
} catch (e) {
window.whatsappManager.showError('Error: ' + e.message);
}
};
window.uploadWhatsAppProfilePhoto = async function() {
const fileInput = document.getElementById('wp-photo-file');
if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
alert('Selecciona una foto primero');
return;
}
const formData = new FormData();
formData.append('photo', fileInput.files[0]);
try {
window.whatsappManager.showInfo('Subiendo foto de perfil...');
const baseUrl = window.whatsappManager.baseUrl || 'api/';
const response = await fetch(baseUrl + 'upload_whatsapp_profile_photo.php', {
method: 'POST',
body: formData,
credentials: 'same-origin',
});
const res = await response.json();
if (res && res.success) {
window.whatsappManager.showSuccess(res.message || 'Foto actualizada correctamente');
// Actualizar preview local
const reader = new FileReader();
reader.onload = (e) => {
const img = document.getElementById('wp-profile-photo-preview');
const ph = document.getElementById('wp-profile-photo-placeholder');
if (img) { img.src = e.target.result; img.style.display = 'inline-block'; }
if (ph) { ph.style.display = 'none'; }
};
reader.readAsDataURL(fileInput.files[0]);
fileInput.value = '';
} else {
window.whatsappManager.showError(res?.error || 'Error al subir la foto');
}
} catch (e) {
window.whatsappManager.showError('Error: ' + e.message);
}
};
// Cargar perfil al abrir la pestaña
document.addEventListener('DOMContentLoaded', () => {
const profileLinks = document.querySelectorAll('[data-tab="whatsapp_profile"]');
profileLinks.forEach(link => {
link.addEventListener('click', () => {
// Pequeño delay para que el tab esté visible
setTimeout(() => window.loadWhatsAppProfile && window.loadWhatsAppProfile(), 100);
});
});
});
// ─────────────────────────────────────────────────────────────────────────────
// RESET + RE-SINCRONIZACIÓN DE PLANTILLAS
// ─────────────────────────────────────────────────────────────────────────────
window.resetAndSyncTemplates = async function() {
if (!window.whatsappManager) { alert('Error: Sistema no inicializado'); return; }
const confirmed = confirm(
'⚠️ ATENCIÓN: Esta acción eliminará TODAS las plantillas locales y las volverá a importar desde WhatsApp/Facebook.\n\n' +
'¿Estás seguro de que deseas continuar?'
);
if (!confirmed) return;
const btn = document.getElementById('btn-reset-sync-templates');
if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Procesando...'; }
try {
window.whatsappManager.showInfo('Eliminando plantillas locales y re-sincronizando desde WhatsApp...');
const response = await window.whatsappManager.apiCall('reset_and_sync_templates.php', { method: 'POST' });
if (response && response.success) {
const d = response.data || {};
const msg = `${response.message}\n• Recibidas de Facebook: ${d.total_facebook || 0}\n• Importadas: ${d.imported || 0}${d.errors?.length ? '\n⚠️ ' + d.errors.length + ' errores' : ''}`;
window.whatsappManager.showSuccess(msg);
if (window.whatsappManager.loadTemplates) window.whatsappManager.loadTemplates();
} else {
window.whatsappManager.showError(response?.error || 'Error desconocido al re-sincronizar');
}
} catch (e) {
window.whatsappManager.showError('Error de conexión: ' + e.message);
} finally {
if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-trash-restore"></i> Limpiar y Re-sincronizar'; }
}
};
};