sorrisosrs / Gerador de Relatorios

// ==UserScript==
// @name         Gerador de Relatorios
// @namespace    http*://itown-saraiva.cloudapp.net/*
// @version     1.0.274
// @description Gerador de relatorios para ITOWN
// @copyright   2014+, Wesley Nascimento
// @author      Wesley Nascimento
// ==/UserScript==

/* REGEXP */

    
/* Injeção no HTML */
    
$(document).ready( function(){    
    //Cria modulos
    var modulos = [];    
    modulos.push( new RelatorioDomingos() );
    
    for(var m in modulos ){
        m = modulos[m];
        m.start();
    }
});

/* Objetos de modulos */
function RelatorioDomingos(){
    var $html, $progress;
    var workPage =  'ListClosed';
    var incrementer = 0;
    var report = {};
    
    
    //Constuctor
    (function(){
    	if( hasSession() ){
        	report = JSON.parse( localStorage.getItem('session_report') );
        }
    })();
    
    function start(){ 
        var loc = location.href;
        if( loc.indexOf( workPage ) > -1  ){
            bind();            
            execute();
        }
    }
    
    //Adiciona Botão de gerar relatorio
    function bind(){
        var $body = $('body');
        var $button = $('<input type="button" value="Gerar Relatorio">');
        $button.on('click', function(){
        	execute( true );
        });
        
        
        $html = $('<div style="border: 1px solid #000; position: fixed; width: 300px; top: 100px; right: 100px; display: none; background: #fff; text-align: center; padding: 5px;"></div>');
        $progress = $('<div><span></span></div>');
        
        $html.append( $progress );
        
        $body.find('#main form p:eq(-1)').append( $button );
        $body.append( $html );
    }
    
   function execute( newSession ){
    	//Se existe uma sessão iniciada, 
        //e não estiver configurado para iniciar uma nova Session
        //Continua apartir da ultima Session
        if( hasSession() ){
            logic();
        }        
        //Deleta a session anterior caso exista e começa denovo.
        else if ( newSession ){
        	cleanSession();
            logic();
        }
    }
    
    //Executa a Logica do negocio
    function logic(){
        $html.show();
        report.status = true;
    
        var $scroller = $('div.scroller tr');
        var max = $scroller.length - 1;
        
        $scroller.each(function(index, value){
        	if( index === 0 ){
                return true;
            }
            
            var $this = $( this );
            
            var $os_id = $this.find("td:eq(0)");
            $os_id.css("color", "rgb(243, 85, 3)");
            var os_number = $os_id.text().match(/\d+/)[0];
            
            var details_url = '/ServiceOrder/Details';
            
            $.post( details_url, { id : os_number }, function( html ){
            	parseDetails( $(html) , max);
            });
            
        });
    }
    
    function parseDetails( $html, max ){
        ++incrementer;        
        $progress.html(incrementer + "/" + max);
        
        var $table = $html.find('table:eq(0)');
        var first_date_text = $table.find('tr:eq(1) td:eq(0)').text();
        var last_date_text = $table.find('tr:eq(-1) td:eq(0)').text();
        
        var first_date_date = mileToDate( stringToMile( first_date_text ) );
        var last_date_date = mileToDate( stringToMile( last_date_text ) );
                
        if( first_date_date.getDay() === 0 ){
            var day = first_date_date.getDate() + "/" + (first_date_date.getMonth() + 1);
            
            incrementField(day, 'open');
        }
        
        if( last_date_date.getDay() === 0 ){
            var day = last_date_date.getDate() + "/" + (last_date_date.getMonth() + 1);
            
            incrementField(day, 'closed')
            
            var $table_quotation = $html.find('table:eq(1)');
        	
            //Se foi fechado no domingo pega o valor recebido
            if( $table_quotation.find('tr').length > 1 ){
                var value = $table_quotation.find('tr:eq(-1) td:eq(4)').text();
                var money = Number( value.match(/\d+/)[0] );
                
                incrementField(day, 'oow', money);
            }
        }       
               
        
        //Se for o ultimo item, salva o report
        if(incrementer == max ){
            var result = appendToSession( report );
            showNext( result );
        }
    }
    
    function showNext( result ){
        
        var $skip = $('body').find('.PagedList-skipToNext');
        if( !$skip.hasClass('disabled') ){
        	var url = $skip.find('a').attr("href");
            if( typeof url !== "undefined")
            	location.href = url;
        } else {
            //Mostrar resultado antes de limpar
            var open = 0,
                closed = 0, 
                oow = 0,
                length = 0;
            
			var html = '';
			html += '<table width="100%">';
            	html += '<tbody>';
            	html += '<tr><th>Ref</th><th>Abertas</th><th>Fechadas</th><th>OOW</th></tr>';
            	for(var day in result){
                    if( day == "status" ) continue;
                    
                    var row = result[day];
                    html += '<tr><td>'+ day +'</td><td>' + row.open + '</td><td>' + row.closed + '</td><td>' + row.oow.formatMoney(2, ',', '.') + '</td></tr>';
                    open += row.open;
                    closed += row.closed;
                    oow += row.oow;
                    length++;
                }
            	html += '<tr><td>Total</td><td>' + open + '</td><td>' + closed + '</td><td>' + oow.formatMoney(2, ',', '.') + '</td></tr>';
            	html += '<tr><td>Média</td><td colspan="3">' + (oow / length).formatMoney(2, ',', '.') + '</td></tr>';
            	html += '</tbody>';
            html += '</table>';
            
            $progress.html('Relatório');
			$html.append( html );            
        	cleanSession();            
        }
    }
    
    function incrementField(parent, field, val){
        if ( typeof report[parent] == "undefined" ){
        	report[parent] = {
                open : 0,
                closed : 0,
                oow : 0,
            };
        } 
        
        if( typeof val !== "undefined" ){
            report[parent][field] += val ;
        } else {
        	report[parent][field]++;
        }
    }    
    
    //Verifica se já existe uma Session
    function hasSession(){
        var session_report = localStorage.getItem('session_report');
        if(  session_report === null ){
            return false;
        }
        try{
        	var json = JSON.parse( session_report ); 
        } catch ( e ){
            return false;
        }
        
        if( typeof json.status == "undefined"){
        	return false;
        }
        
        return json.status;
    }
    
    //Adiciona informações a Session Atual
    function appendToSession( json ){        
        localStorage.setItem("session_report", JSON.stringify( json ) );
        return json;
    }
    
    //Limpa a Session do navegador
    function cleanSession(){
        localStorage.removeItem("session_report");
    }
    
    //Converte um numero de milesegundos para um objeto Date
    function mileToDate( mile ){
    	return new Date( mile );
    }
    
    //Converte um texto no formate de "dd/mm/YYYY H:i:s" em um numero de milesegundos
    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();                        
    }
    
    //Methodos publicos
    return {
        start : start
    }    
}

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return "R$ " + sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};