DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`quadre_clientes`(IN datFEC DATETIME)
BEGIN


 DECLARE datSTART DATE;
 SET datFEC =  TIMESTAMP(datFEC,'23:59:59');
 SELECT util.firstDayOfYear(datFEC) INTO datSTART;

 SELECT P2.Alias, C.Id_Cliente, C.Cuenta, Gestion, Contaplus, Gestion - Contaplus as Diferencia, empresa_id, Cliente
 
 FROM Clientes C
 
 JOIN pay_met pm ON pm.id = C.pay_met_id
 
 JOIN
 
 (

 SELECT empresa_id, Id_Cliente, round(sum(Gestion),2) as Gestion, round(sum(Contaplus),2) as Contaplus 
 
 FROM
 
 (
            SELECT empresa_id, Id_Cliente, Gestion, 0 as Contaplus
     
            FROM
            
               (
                    SELECT empresa_id, Id_Cliente, -1 * Importe as Gestion
                    FROM Facturas 
                    WHERE Fecha BETWEEN datSTART AND datFEC
                    UNION ALL 
                    SELECT empresa_id, Id_Cliente, Entregado
                    FROM Recibos
                    WHERE Fechacobro BETWEEN datSTART AND datFEC
               ) G 
            
            WHERE empresa_id <> 965
            
            UNION ALL
 
            SELECT empresa_id, Id_Cliente, 0, round(nz(Eurohaber) - nz(Eurodebe),2) as Contaplus
            
            FROM bi.XDiario_ALL XD
            
            JOIN Clientes C ON C.Cuenta = XD.SUBCTA
            
            WHERE Fecha BETWEEN datSTART AND datFEC
             
 ) sub1
  
 GROUP BY empresa_id, Id_Cliente
 
 ) sub2 USING(Id_Cliente)
 
 JOIN Proveedores P2 ON P2.Id_Proveedor = sub2.empresa_id
 
 WHERE pm.deudaviva -- Cliente de perdidas no vale la pena revisarlo 
  
 HAVING ABS(Diferencia) > 0.05
 
 ORDER BY Cliente;
            

END$$
DELIMITER ;
