call spQuery_Packing_Mercaderia(1, '2012-02-07',NULL,'');

DROP PROCEDURE IF EXISTS spQuery_Packing_Mercaderia;
CREATE PROCEDURE spQuery_Packing_Mercaderia(
  varEmpresa  int,
  varFecha    date,
  varVendedor text,
  varRuta     text
  )
BEGIN
  DECLARE varCadVen, varCadRut TEXT DEFAULT '';
  
	if varVendedor <> '' AND varVendedor <> 'Todos' then
    set varCadVen = CONCAT(" and V.id_trabajador in ", varVendedor);
  end if;
  if varRuta <> '' 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 CASE WHEN D.id_tipo='B' THEN 'BONIFICACION' ELSE 'VENTA' END ",
                    "       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) as CANTIDAD, ",
                    "sum(D.total) 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 ",
                    "inner join _sv_cliente C ON V.id_cliente = C.id_cliente ",
                    "where V.fecha_emision = '", varFecha, "' ",
                    "AND V._estado = 'A' ",
                    "AND D._estado = 'A' ",
                    "AND V.estado <> 'AN' ",
                    "AND V.id_empresa = ", varEmpresa, " ",
                    varCadVen, varCadRut,
                    "group by CASE WHEN V.id_tipo_doc = 5 ",
                    "              THEN 'CAMBIO' ",
                    "              ELSE CASE WHEN D.id_tipo='B' THEN 'BONIFICACION' ELSE 'VENTA' END ",
                    "         END, D.id_producto, P.descripcion, D.id_um ",
                    "order by CASE WHEN V.id_tipo_doc = 5 ",
                    "              THEN 'CAMBIO' ",
                    "              ELSE CASE WHEN D.id_tipo='B' THEN 'BONIFICACION' ELSE 'VENTA' END ",
                    "         END desc, P.id_proveedor, P.descripcion");
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;