call spQuery_Packing_Devolucion(1, '2013-01-24',NULL,NULL);

DROP PROCEDURE IF EXISTS spQuery_Packing_Devolucion;
CREATE PROCEDURE spQuery_Packing_Devolucion(
  varEmpresa  int,
  varFecha    date,
  varVendedor text,
  varRuta     text
  )
BEGIN
  DECLARE varCadVen, varCadRut TEXT DEFAULT '';
  
	if varVendedor <> '' and varVendedor <> 'Todos' and varVendedor is not null then
    set varCadVen = CONCAT(" and V.id_trabajador in ", varVendedor, " ");
  end if;
  
  if varRuta <> '' and varRuta <> 'Todos' and varRuta is not null then
    set varCadRut = CONCAT(" and V.id_ruta in ", varRuta, " ");
  end if;
  
  SET @sql = CONCAT("select CASE WHEN V.id_tipo_doc = 5 THEN 'CAMBIO' ELSE 'VENTA' END AS TIPO, ",
                    "D.id_producto as CPRO, P.descripcion as PRODUCTO, D.id_um as UM, ",
                    "count(distinct V.id_cliente) as PDV, ",
                    "sum(D.cantidad_ate - D.cantidad) as CANTIDAD, ",
                    "sum((D.cantidad_ate - D.cantidad)*D.precio) as MONTO ",
                    "from _sv_venta_detalle D ",
                    "inner join _sv_venta V    ON D.id_venta = V.id_venta ",
                    "inner join _sv_producto P ON D.id_producto = P.id_producto ",
                    "where V.fecha_emision = '", varFecha, "' ",
                    "and V.id_empresa = ", varEmpresa, " ",
                    "and D.cantidad <> D.cantidad_ate ",
                    "and ifnull(V.id_motivo_rechazo,0) <> 0 ",
                    varCadVen, varCadRut,
                    "group by D.id_producto, P.descripcion, D.id_um ",
                    "order by CASE WHEN V.id_tipo_doc = 5 THEN 'CAMBIO' ELSE 'VENTA' END, P.id_proveedor, P.descripcion;");
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1; 
END;