sorrisosrs / Itown

// ==UserScript==
// @name        Itown
// @include     http*://itown-saraiva.cloudapp.net/*
// @version     2.3.382
// @description Algumas coisas uteis para o ITOWN
// @copyright   2014+, Wesley Nascimento
// @author      Wesley Nascimento
// ==/UserScript==
 
(function(){
        var loc = location.href;
   
    //Na pagina de criar OS
    if( StringHas( loc, "ServiceOrder/Create") ){
        bindSOCreate();
    }
    //Na pagina de criar ou editar cadastro do cliente
    else if( StringHas( loc, "Customer/Create" ) || StringHas( loc, "Customer/Edit" ) ){
        bindCCreate();
    } 
    //Na pagina de encerrar OS
    else if( StringHas( loc, "History/Close" ) ){
        bindSOFinish();
    }
    //Na pagina da lista de OS resolvidas
    else if( StringHas( loc, "ServiceOrder/ListResolved" ) ){
        bindSOResolvedList();
    }
   
})();
 
//Uteis
function StringHas( string , search){ if( string.indexOf( search )  > -1 ){ return true;  } return false; }
 
function isNumeric(str) { var er = /^[0-9]+$/;   return (er.test(str)); }

function stringToMile(str){
    str = str.replace(/  /g, '');
    
	var date = str.split(" ")[0];
    var time = str.split(" ")[1];
    
    var day = date.split("/")[0],
        month = date.split("/")[1] - 1, //Fiz month number
        year = date.split("/")[2];
    
    var hours = time.split(":")[0],
        minutes = time.split(":")[1],
        seconds = time.split(":")[2];
                               
   return new Date(year, month, day, hours, minutes, seconds, 0).getTime();                        
}
 
//Complexas
function bindCCreate(){
    var $zip = $("#ZipCode");
    
    $buscarceperror = $("<p class='field-validation-error'></p>");
    $zip.parent().append( $buscarceperror );
    
    $zip.on("keyup", function(){
        var zip = $(this).val().replace(/\D/g, "");
       
        if(zip !== null && zip.length === 8 && isNumeric( zip )){
            $buscarceperror.text("");
            receiveCEP( zip );
        } else if(zip.length > 8){
            $buscarceperror.text("O cep nao esta no formato correto. Ex: (xxxxxxxx) 8 numeros.");
        }
    });
    
    var $error = $('<span class="field-validation-error"></span>');
    
    var $cpf = $("#CPF");
    $cpf.parent().append( $error );
    $cpf.on("keyup", function(){
        var cpf = $(this).val();
        if( cpf.length == 11 ){
            $.post("/Customer", {cpf: cpf},function( html ){
                var $table_tr = $(html).find("#main table tr");
                
                if( $table_tr.length > 1 ){
                    var id = $table_tr.find("td:eq(0)").text();
                	$error.html('<a href="/ServiceOrder/Create?customerID='+ id +'">Este cpf já foi cadastrado!</a>'); 
                }
            });
        } 
        else if( cpf.length > 11){
        	$error.text("The field Modelo must be a string or array type with a maximum length of '11'.");
        } else {
        	$error.text("");
        }
    });
    
    var $form = $("form");
    
    $form.submit(function( event ){
        var $this = $(this);
        
        var submits = $this.attr("data-submits");
        	submits = submits === null ? 0 : submits;        
        
        $this.attr("data-submits", ++submits );
        
        if( submits == 1){
            alert("Já revisou os dados?");            
            event.preventDefault();
            return false;
        }
        else if( submits == 2){
            return true;
        }
        else if( submits > 2 ) {
        	event.preventDefault();
            return false;
        }
                
    });
    
    $("input").on("keyup", function( key ){
    	$form.attr("data-submits", 0);
    });
}

function bindSOFinish(){
	var $form = $("form");
    
    $form.submit(function( event ){
        var $this = $(this);
        
        var submits = $this.attr("data-submits");
        	submits = submits === null ? 0 : submits;        
        
        $this.attr("data-submits", ++submits );
        
        if( submits == 1){
            alert("Já revisou os dados?");            
            event.preventDefault();
            return false;
        }
        else if( submits == 2){
            return true;
        }
        else if( submits > 2 ) {
        	event.preventDefault();
            return false;
        }
                
    });
    
    $("input").on("keyup", function( key ){
    	$form.attr("data-submits", 0);
    });
}
 
function receiveCEP( zipCode ){
    var $state = $("#State"),
        $city = $("#City"),
        $address = $("#Address"),
    	$error = $("#buscarceperro");
    
    $state.val( "Buscando..." );
    $city.val( "Buscando..." );
    $address.val( "Buscando..." );
    
    var url = "http://apps.widenet.com.br/busca-cep/"+ zipCode+".json?callback=?";
    
    $.get("http://apps.widenet.com.br/busca-cep/api/cep.json?code=" + zipCode,
         function(data){
             if(data.status == 1) {              
                $address.val(data.address + ", X - "+ data.district);
                $city.val( data.city );
                $state.val( data.state );
             } else {
             	$error.text("CEP não encontrado!");            
                $address.val("");
                $city.val("");
                $state.val("");
             }
         });
}
 
function bindSOCreate(){ 
   
    $("#CoverageOption").on('change', function(){       
        var selected = $(this).val();
        var $obs = $("#Observations");
        var $eq = $("#EquipmentDescription");
        
        if( $("#Observations").val().length > 0 ){
                return;
        }
        switch( selected ){
            case "OOW":
                $obs.val("Entregue o SimCard ao cliente, deixado somente o aparelho.\n"+
                                        "Cliente ciente do valor de R$ xxx,xx pela substituição do aparelho podendo ser parcelado em até X vezes.\n"+
                                        "Descrição completa do aparelho.");
                $eq.val("OOW");
                break;
            case "Guarantee":
                $obs.val("Entregue o SimCard ao cliente, deixado somente o aparelho.\n"+
                             "Descrição completa do aparelho.");
                $eq.val("Em garantia");
                break;
            case "Verify":
                $eq.val("Em verificação");
                $obs.val("Entregue o SimCard ao cliente, deixado somente o aparelho.\n"+
                                        "Cliente ciente de que o aparelho foi deixado para verificação.\n"+
                                        "Descrição completa do aparelho.");
                break;
            case "GE":
                $obs.val("Entregue o SimCard ao cliente, deixado somente o aparelho.\n"+
                                                "Descrição completa do aparelho.");
                break;
        }
    });
   
    var $form = $("form");
    
    $form.submit(function( event ){
        var $this = $(this);
        
        var submits = $this.attr("data-submits");
        	submits = submits === null ? 0 : submits;        
        
        $this.attr("data-submits", ++submits );
        
        if( submits == 1){
            alert("Já revisou os dados?");            
            event.preventDefault();
            return false;
        }
        else if( submits == 2){
            return true;
        }
        else if( submits > 2 ) {
        	event.preventDefault();
            return false;
        }
                
    });
    
    $("input").on("keyup", function( key ){
    	$form.attr("data-submits", 0);
    });
   
    var $model = $("#EquipmentModel");
    
    $model.parent().append('<span class="field-validation-error" id="errorModel"></span>');
   
    $model.on("keyup", function( key ){
        if( $(this).val().length > 20 ){
                $("#errorModel").text("The field Modelo must be a string or array type with a maximum length of '20'.");
        } else {
                $("#errorModel").text("");
        }
    });
}

function bindSOResolvedList(){
    var $inputBox = $('<div style="background: #CCC;color: #000; border: 2px solid #333;display: none;position: absolute;width: 500px;opacity: 0.8;"></div>');
    
    
    $(".scroller tr").each(function(index, value){
        if( index === 0 ){
            return true;
        }
        
        var $this = $( this );
        
        var $os_id = $this.find("td:eq(0)");
        	$os_id.css("color", "#034af3");
        var $customerName = $this.find("td:eq(3)");
        
        var os_number = $os_id.text().match(/\d+/)[0];
        
        var url = "http://wesleynascimento.net/cross-domain/itown.class.php?callback=?&get";
            
       	$.getJSON(url, "os_id="+ os_number, function( result ){
            var data = result.data;
            if( data.length > 0 ){
                $os_id.css("font-weight", "bold");
        	}
        });
        
        $customerName.on("mouseover", function( event ){
            
            $.post("/ServiceOrder/Details/" + os_number,  function( html ){
            	var $html = $( html );
                var cpf = $html.find("#Customer_CPF").val();
                console.log();
                $.post("/Customer", {cpf: cpf},function( html ){
                    var $html = $( html ); 
                    var $table_tr = $html.find("#main table tr");
                    
                    if( $table_tr.length > 0 &&  $table_tr.length < 5){
                        var tel_1 = $table_tr.find("td:eq(3)").text();
                        var tel_2 = $table_tr.find("td:eq(4)").text();
                        var cidade = $table_tr.find("td:eq(7)").text();
                        
                        var html = '<table width="100%" style="padding: 10px"><tbody>';                     
                        html += '<tr><td>Telefone:</td><td>' + tel_1 + '</td></tr>';
                        html += '<tr><td>Telefone:</td><td>' + tel_2 + '</td></tr>';
                        html += '<tr><td>Cidade:</td><td>' + cidade + '</td></tr>';
                        html += '</tbody></table>';
                        $inputBox.html( html );
                        $inputBox.css("top", event.pageY + "px");
                        $inputBox.css("left", event.pageX + "px");                    
                        $inputBox.show();
                        
                    }
                });               
            });
        });
        
        $customerName.on("mouseout", function(){
        	$inputBox.hide();
        });
        
        $os_id.on("mouseover", function( event ){
            
            var url = "http://wesleynascimento.net/cross-domain/itown.class.php?callback=?&get";
            
            $.getJSON(url, "os_id="+ os_number, function( result ){
                var data = result.data;
                if( data.length > 0 ){
                    var html = '<table width="100%" style="padding: 10px"><tbody>';
                    html += '<tr><th width="20%">Data</th><th width="30%">Responsável</th><th width="50%">Notas</th></tr>';
                    
                    for( var i = 0; i < data.length; i++){
                        var date = new Date( Number( data[i]['date']) );
                        
                        html += '<tr><td>' + date.toLocaleString() + '</td><td>' + data[i]['author'] + '</td><td>' + data[i]['notes'] + '</td></tr>';
                    }
                    html += '</tbody></table>';
                    $inputBox.html( html );
                    $inputBox.css("top", event.pageY + "px");
                    $inputBox.css("left", event.pageX + "px");                    
                    $inputBox.show();
                }
            });
        });
        
        $os_id.on("mouseout", function(){
        	$inputBox.hide();
        });
        
        $os_id.on("click", function(){
        	//Input pra adicionar notas            
            var notes = prompt("Digite a notas a serem adicionadas a esta OS:", "");
            
            if( notes != "" && notes != null && notes.length > 0 ){
                //var os_number = $os_id.text().match(/\d+/)[0];//replace(/^\D+/g, '');                
                var author = $("#logindisplay strong").text();
                
            	var url = "http://wesleynascimento.net/cross-domain/itown.class.php?callback=?&set";
                
                $.getJSON(url, { os_id: os_number, author : author, notes : notes, date : new Date().getTime() }, function(){
                	$os_id.on("mouseover");
                });
            }
        }); 
        
        var $changeDate = $this.find("td:eq(4)");
        
        var sevenDays = 7 * 24 * 60 * 60 * 1000;
        var threeDays = 3 * 24 * 60 * 60 * 1000;
        
        var time = stringToMile( $changeDate.text() );
        var now = new Date().getTime();
        
        if(  now - time >= sevenDays ){
            $changeDate.css("color", "#C04646");
        }        
        else if( now - time >= threeDays ){
        	$changeDate.css("color", "#E4B41F");
        }
        
    });
    
    $("body").append( $inputBox );
}