call spQuery_Cuentas_Cobrar(1, NULL, NULL, NULL, NULL, NULL, '2012-08-26', null,null);

DROP PROCEDURE IF EXISTS spQuery_Cuentas_Cobrar;
CREATE PROCEDURE spQuery_Cuentas_Cobrar(
  varEmpresa  int,
	varCliente  int,
  varVendedor text,
  varRuta     text,
  varTipoDoc  int,
  varFechaIni date,
  varFechaFin date,
  varField    varchar(60),
  varOrder    varchar(5)
)
BEGIN 
  DECLARE varCadEmp, varCadCli, varCadVen, varCadRut, varCadTip, varCadIni, varCadFin varchar(100) DEFAULT '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  IF varEmpresa  <> '' and varEmpresa is not null THEN
    SET varCadEmp = CONCAT(" and V.id_empresa = ", varEmpresa);
  END IF; 
  IF varCliente  <> '' and varCliente is not null THEN
    SET varCadCli = CONCAT(" and V.id_cliente = ", varCliente);
  END IF;  
  if varVendedor <> '' and varVendedor is not null 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;
  
  IF varTipoDoc <> '' and varTipoDoc is not null THEN
    SET varCadTip = CONCAT(" and V.id_tipo_doc = ", varTipoDoc);
  END IF;
  IF varFechaIni  <> '' and varFechaIni is not null THEN
    SET varCadIni = CONCAT(" and V.fecha_emision >= '", varFechaIni, "' ");
  END IF;
  IF varFechaFin <> '' and varFechaFin is not null THEN
    SET varCadFin = CONCAT(" and V.fecha_emision <= '", varFechaFin, "' ");
  END IF;
  
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'V._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'V._date_update'
                        ELSE varField
                   END;
    SET varCadOrd = CONCAT("ORDER BY ", varField, " ");
    IF varOrder is not null and varOrder <> '' THEN
      SET varCadOrd = CONCAT(varCadOrd, varOrder, " ");      
    END IF;
  END IF;
  
  SET @sql = CONCAT("select V.id_venta as IDE, ",
                    "V.id_empresa as CEMP, E.nombre as EMPRESA, ",
                    "date_format(V.fecha_emision,'%d/%m/%Y')  as FEMI, ",
                    "date_format(V.fecha_vencimiento,'%d/%m/%Y')  as FVEN, ",
                    "DATEDIFF(V.fecha_vencimiento, V.fecha_emision) as DIASV, ",
                    "concat(TD.abrev,' ', V.nro_serie,'-', V.nro_preimpreso) as DOCUMENTO, ",
                    "V.id_condicion as CCON, TC.nombre as CONDICION, ",
                    "V.id_cliente as CCLI, C.nombre as CLIENTE, ",
                    "C.DIRECCION, C.id_ruta as CRUT, R.nombre as RUTA, ",
                    "V.id_trabajador as CVEN, concat(ifnull(Ve.apellido_paterno,''),' ', ifnull(Ve.apellido_materno,''),' ', ifnull(Ve.nombre,'')) as VENDEDOR, ",
                    "V.TOTAL, IFNULL(V.total,0) - IFNULL(V.saldo,0) as PAGOS, IFNULL(V.SALDO,0) AS SALDO, ",
                    "date_format(C._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(C._date_update,'%d/%m/%Y %h:%i:%s %p') AS FECHA_MODIFI, ",
                    "UPPER(UN.usuario) as USER_CREADO, ",
                    "UPPER(UU.usuario) as USER_MODIFI, ",
                    "NULL AS PAGAR ",
                    "from _sv_venta V ",
                    "inner join _sv_empresa        E ON V.id_empresa = E.id_empresa ",
                    "inner join _sv_cliente        C ON V.id_cliente = C.id_cliente ",
                    "inner join _sv_ruta           R ON V.id_ruta = R.id_ruta ",
                    "inner join _sv_trabajador    Ve ON V.id_trabajador = Ve.id_trabajador ",                    
                    "inner join _sv_tipo_doc_venta TD ON V.id_tipo_doc = TD.id_tipo_doc ",
                    "inner join _sv_tipo_condicion TC ON V.id_condicion = TC.id_condicion ",                    
                    "left join _sys_usuario       UN ON V._user_create = UN.id_usuario ",
                    "left join _sys_usuario       UU ON V._user_update = UU.id_usuario ",
                    "where V.estado not in ('AN','CA') ",
                    "AND IFNULL(V.SALDO,0) > 0 ",
                    varCadEmp, varCadCli, varCadVen, varCadRut, varCadTip, varCadIni, varCadFin,
                    varCadOrd);
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;
