/* ============================================================ * CONTACTAR AL VENDEDOR (Tienda) * ------------------------------------------------------------ * - Pre-chequea conexiones de comprador y vendedor * - Verifica estados de identidad / comercial * - Muestra el modal dinámico con recarga gratis (fase β) * - Crea (o recupera) la negociación y redirige al chat * ============================================================ */ (function ($) { /* helpers genéricos que ya tienes en customAlerts.js ------------- */ const toast = window.mostrarToast || ((m)=>alert(m)); const modalSimple = window.mostrarModalDinamico|| ((t,m)=>alert(`${t}\n${m}`)); const alertaCarga = window.mostrarAlertaCargando; const alertaError = window.mostrarAlertaError; const alertaExito = window.mostrarAlertaExito; const confirmar = window.mostrarModalConfirmacion; /* Elementos fijos del DOM --------------------------------------- */ const $modal = $('#modalContacto'); const $modalBody = $('#modalContactoBody'); // debes dejarlo vacío en el HTML const $btnConfirmar = $('#btnConfirmarContacto'); /* util: crea bloque de recarga gratis --------------------------- */ function bloqueRecargaGratis() { return `
Fase Beta – Recarga gratis para probar la plataforma.
`; } function getInt($el) { const val = parseInt($el, 10); return isNaN(val) ? 0 : val; } function tieneConexionesSuficientes(saldo, necesita) { return getInt(saldo) >= getInt(necesita); } /* =============================================================== * 1. Click “Contactar al vendedor” * =============================================================== */ $(document).on('click', '#btnContactarVendedor', function (e) { e.preventDefault(); /* IDs */ const compradorID = +$('#usuario_id').val(); const vendedorID = +$(this).data('vendedor-id'); const necesidadID = +$(this).data('necesidad-id'); if (!compradorID) { mostrarModalConfirmacion('Queres iniciar sesión ahora?.', function () { const cleanPath = location.pathname.substring(1); // remueve el primer "/" location.href = '/login?redirect=' + cleanPath; },'Inicia sesión para continuar'); return; } if (compradorID === vendedorID) { toast('No puedes contactar tu propia publicación','warning'); return; } /* ---- ① Pre-chequeo de conexiones ---- */ $.getJSON('/cfc/ajax/ajax_negociaciones.cfc?method=preChequeoContacto', { comprador_id: compradorID, vendedor_id : vendedorID, necesidad_id: necesidadID }) .done(function (r) { /* ---------- bloqueado por saldo ---------- */ if (!r.OK) { if (r.RAZON === 'comprador_sin_conex') { /* saldo_comprador / necesita_comprador */ pintarModalFaltaConexiones(r.SALDO_COMPRADOR, r.NECESITA_COMPRADOR, r.FASE); $modal.modal('show'); } else if (r.RAZON === 'vendedor_sin_conex') { //toast(`El vendedor necesita ${r.NECESITA_VENDEDOR} 🔗 para recibir más contactos`, 'info'); } return; // cortamos aquí } /* ---------- ② estados de verificación ---------- */ $.getJSON('/cfc/ajax/ajax_verificacion.cfc?method=verificarEstadoDoble', { comprador_id: compradorID, vendedor_id : vendedorID }).done(function (ver) { const bloqueo = analizarVerificacion(ver); if (bloqueo) { mostrarModalVerificacion(bloqueo); return; } /* ---------- ③ confirmación final ---------- */ confirmar( `Esta acción consume ${r.COSTO_COMPRADOR} 🔗 conexiones. Confirmas?`, () => iniciarNegociacion(compradorID, vendedorID, necesidadID),'Contactar al Vendedor' ); }); }) .fail(() => alertaError('Error al chequear saldo de conexiones')); }); /* =============================================================== * 2. Modal de verificación (bloqueos) * =============================================================== */ function mostrarModalVerificacion(estado) { let titulo = '🛡️ Verificación requerida'; let mensaje = '', txtOK = 'Entendido', txtKO = 'Cancelar', accionOK = () => $modal.modal('hide'), mostrarKO = false; switch (estado) { case 'identidad_pendiente': mensaje = 'Debes verificar tu identidad antes de contactar vendedores.'; txtOK = 'Verificar mi identidad'; mostrarKO = true; accionOK = () => location.href = '/dashboard#tab-vericom'; break; case 'identidad_revision': mensaje = 'Tus documentos están en revisión. Te avisaremos pronto.'; break; case 'identidad_rechazada': mensaje = 'La verificación fue rechazada. Sube nuevamente la documentación.'; txtOK = 'Reintentar verificación'; mostrarKO = true; accionOK = () => location.href = '/dashboard#tab-vericom'; break; case 'comercial_pendiente': mensaje = 'Completa la verificación comercial para operar como vendedor.'; txtOK = 'Verificación comercial'; mostrarKO = true; accionOK = () => location.href = '/dashboard#tab-vericom'; break; case 'comercial_revision': mensaje = 'Tu información comercial se está revisando.'; break; case 'comercial_rechazada': mensaje = 'Verificación comercial rechazada. Sube nuevamente la constancia fiscal.'; txtOK = 'Reintentar verificación'; mostrarKO = true; accionOK = () => location.href = '/dashboard#tab-vericom'; break; default: mensaje = 'Debes completar tu verificación para continuar.'; txtOK = 'Ir a mi panel'; accionOK = () => location.href = '/dashboard#tab-vericom'; } $('#modalVerificacionTitulo').text(titulo); $('#modalVerificacionMensaje').html(mensaje); $('#btnPrincipalVerificacion').text(txtOK).off('click').on('click', accionOK); if (mostrarKO) { $('#btnSecundarioVerificacion') .text(txtKO).removeClass('d-none') .off('click').on('click', () => $('#modalVerificacion').modal('hide')); } else { $('#btnSecundarioVerificacion').addClass('d-none'); } $('#modalVerificacion').modal('show'); } /* =============================================================== * 3. Modal de falta de conexiones (fase β) – cuerpo dinámico * =============================================================== */ function pintarModalFaltaConexiones(saldo, necesita, fase) { let html = ''; if (tieneConexionesSuficientes(saldo, necesita)) { $btnConfirmar.prop('disabled', false); $modal.modal('hide'); return; } if (fase === 'beta') { html = `
No tienes conexiones suficientes.
Saldo actual: ${saldo} 🔗
Necesitás: ${necesita} 🔗
${bloqueRecargaGratis()} `; } else { html = `
Comprar Conexiones
`; } $modalBody.html(html); $btnConfirmar.prop('disabled', true); } /** * Recarga gratis (fase β) si el usuario no llega al mínimo requerido. * Llama al callback cuando el usuario YA tiene saldo suficiente. */ function recargarSiNecesita(usuarioId, saldo, necesita, done) { if (saldo >= necesita) { // ya alcanza done(); return; } $.ajax({ url : '/cfc/ajax/ajax_conexiones.cfc?method=recargaBetaGratis', type: 'POST', dataType: 'json', data: { usuario_id: usuarioId }, success (r) { if (r.SUCCESS === true || r.success === true) { toast('Se acreditaron 10 conexiones gratis', 'success'); done(); // nuevo saldo ≥ necesita (garantizado) } else { toast('Error al recargar: ' + (r.ERROR||''), 'danger'); } }, error () { toast('Error de red al recargar', 'danger'); } }); } function recargarSiNecesita2(usuarioId, saldo, necesita, done) { if (saldo >= necesita) { done(); return; } $.ajax({ url : '/cfc/ajax/ajax_conexiones.cfc?method=recargaBetaGratis', type: 'POST', dataType: 'json', data: { usuario_id: usuarioId }, success (r) { const nuevoSaldo = getInt(r.SALDO || r.saldo || 0); const ok = r.SUCCESS === true || r.success === true; if (ok && nuevoSaldo >= necesita) { toast('Se acreditaron 10 conexiones gratis', 'success'); done(); } else if (ok && nuevoSaldo < necesita) { toast('No se pudo recargar el saldo suficiente', 'danger'); } else { toast('Error al recargar: ' + (r.ERROR || 'Desconocido'), 'danger'); } }, error () { toast('Error de red al intentar recargar', 'danger'); } }); } /* =============================================================== * 4. Recarga gratis (solo beta) – handler * =============================================================== */ $(document).on('click', '.btn-recarga-gratis', function (e) { e.preventDefault(); e.stopPropagation(); const $btn = $(this).prop('disabled', true) .html('Recargando…'); const compradorId = $('#usuario_id').val(); const vendedorId = $('#necesidadUsuarioID').val(); const saldoCompr = getInt($('#conexiones_disponibles').val()); const saldoVend = getInt($('#saldo_vendedor').val()); const costoCompr = getInt($('#costo_conex').val()); const costoVend = getInt($('#costo_vend').val()); // ① Recarga comprador (obligatorio) recargarSiNecesita(compradorId, saldoCompr, costoCompr, () => { // ② Luego recarga vendedor si le falta recargarSiNecesita(vendedorId, saldoVend, costoVend, () => { // listo → habilitamos Confirmar $('#btnConfirmarContacto').prop('disabled', false); $btn.remove(); // quita bloque “recargar” // actualiza el saldo de conexiones actualizarSaldoConexiones().then(nuevoSaldo => { pintarModalFaltaConexiones(nuevoSaldo, costoCompr, 'beta'); // ← ahora tiene la variable }); }); }); }); /* =============================================================== * 4.1. Actualiza el saldo de conexiones del usuario * =============================================================== */ function actualizarSaldoConexiones() { return new Promise(function (resolve, reject) { const usuarioID = $('#usuario_id').val(); $.ajax({ url: '/cfc/ajax/ajax_conexiones.cfc?method=getSaldoConexiones', type: 'POST', data: { usuario_id: usuarioID }, dataType: 'json', success: function (res) { if (res.SUCCESS === true || res.success === true) { const nuevoSaldo = getInt(res.SALDO) || 0; $('#conexiones_disponibles').val(nuevoSaldo); resolve(nuevoSaldo); } else { console.error('Error al obtener saldo:', res.MESSAGE || res.message); reject(res.message); } }, error: function (xhr, status, err) { console.error('AJAX error:', err); reject(err); } }); }); } /* =============================================================== * 5. Confirmar y crear la negociación * =============================================================== */ function iniciarNegociacion(compradorID, vendedorID, necesidadID) { alertaCarga('Creando chat…'); $.ajax({ url : '/cfc/ajax/ajax_negociaciones.cfc?method=iniciarNegociacionTienda', type: 'POST', dataType: 'json', data: { comprador_id : compradorID, // usuario en sesión (quien inicia) vendedor_id : vendedorID, // la contraparte necesidad_id : necesidadID, // mismo ID para Necesidades.Operacion=1 (compra) o 2 (tienda) mensaje_inicial : $('#mensaje_inicial').val() || '' } }) .done(function (r) { cerrarAlerta(); if (r.EXISTE == 1 || r.CREADO == 1) { location.href = '/mis-negociaciones/?abrir=' + r.NEGOCIACION_ID; } else { alertaError('No fue posible iniciar la negociación. Intenta más tarde.'); } }) .fail(function(){ cerrarAlerta(); alertaError('Error de red.'); }); } /* =============================================================== * 6. Analiza el objeto de verificación doble y devuelve bloqueo * =============================================================== */ function analizarVerificacion(v) { console.log(v.COMPRADOR.ESTADO, v.VENDEDOR.ESTADO); /* prioridad: identidad comprador → comercial comprador → identidad vendedor… */ if (!(v.COMPRADOR.ESTADO.IDENTIDAD == 'verificado' || v.COMPRADOR.ESTADO.IDENTIDAD == 'VERIFICADO')) return 'identidad_'+v.COMPRADOR.IDENTIDAD; if (!(v.VENDEDOR.ESTADO.IDENTIDAD == 'verificado' || v.VENDEDOR.ESTADO.IDENTIDAD == 'VERIFICADO')) return 'identidad_'+v.VENDEDOR.IDENTIDAD; if (!(v.VENDEDOR.ESTADO.COMERCIAL == 'verificado' || v.VENDEDOR.ESTADO.COMERCIAL == 'VERIFICADO')) return 'comercial_'+v.VENDEDOR.COMERCIAL; return null; // sin bloqueos } })(jQuery); //** Preguntas y respuestas */ $(document).ready(function () { const necesidadID = $('#necesidadId').val(); // Cargar preguntas al iniciar cargarPreguntas(); // Enviar nueva pregunta $('#btnEnviarPregunta').on('click', function () { const texto = $('#nuevaPregunta').val().trim(); if (!texto) { mostrarAlertaError('Debes escribir una pregunta antes de enviarla.'); return; } $.ajax({ url: '/cfc/ajax/ajax_necesidades.cfc?method=guardarPregunta', type: 'POST', dataType: 'json', data: { necesidad_id: necesidadID, pregunta_texto: texto }, success: function (r) { if (r.SUCCESS === true || r.success === true) { $('#nuevaPregunta').val(''); mostrarAlertaExito('Tu pregunta fue enviada.'); cargarPreguntas(); } else { mostrarAlertaError(r.MESSAGE || 'Ocurrió un error al enviar la pregunta.'); } } }); }); function cargarPreguntas() { const necesidadID = $('#necesidadId').val(); $.getJSON('/cfc/ajax/ajax_necesidades.cfc?method=listarPreguntas', { necesidad_id: necesidadID }, function (data) { const contenedor = $('#bloquePreguntas'); contenedor.empty(); if (data.PREGUNTAS.length === 0) { contenedor.append('

Aún no hay preguntas.

'); return; } data.PREGUNTAS.forEach(function (p) { // Formatear fechas const fechaPregunta = formatearFechaBonita(p.FECHA_PREGUNTA); let html = `
${p.PREGUNTA_TEXTO}
Preguntado el ${fechaPregunta}
`; if (p.RESPUESTA_TEXTO) { const fechaRespuestaFormateada = formatearFechaBonita(p.FECHA_RESPUESTA); html += `
${p.RESPUESTA_TEXTO}
Respondido el ${fechaRespuestaFormateada}
`; } else if (data.ES_COMPRADOR) { html += `
`; } html += `
`; contenedor.append(html); }); }); } // Mostrar modal $(document).on('click', '.responder-btn', function () { const id = $(this).data('id'); const preguntaTexto = $(`#pregunta_${id}`).text().trim(); $('#pregunta_id_responder').val(id); $('#respuesta_texto').val(''); $('#pregunta_texto').text(preguntaTexto); // texto seguro desde DOM $('#modalResponder').modal('show'); }); // Enviar respuesta $('#btnEnviarRespuesta').on('click', function () { const respuesta = $('#respuesta_texto').val().trim(); const preguntaID = $('#pregunta_id_responder').val(); if (!respuesta) { mostrarAlertaError('Debes escribir una respuesta.'); return; } $.post('/cfc/ajax/ajax_necesidades.cfc?method=responderPregunta', { pregunta_id: preguntaID, respuesta_texto: respuesta }, function (data) { if (data.SUCCESS === true || data.success === true) { $('#modalResponder').modal('hide'); cargarPreguntas(); } else { mostrarAlertaError('Error al responder la pregunta.'); } }, 'json'); }); });