Friday, July 06, 2012

RSAP, Rook y ERP

Como escribi en mi blog Analytics with SAP and R (Windows version) podemos utilizar RSAP para conectarnos a nuestro ERP y jugar con la data. Esta vez, queria por supuesto, seguir explorando las capacidades de RSAP, pero utilizando algo mas. Como todo el mundo ya sabe, amo los micro-frameworks, asi que para R eso no es una exepcion...afortunadamente, Rook vino al rescate... Rook es un servidor web simple que correra localmente en nuestra PC y nos permitira hacer algunas cosas realmente interesantes...basta de hablar...vayamos al codigo fuente...

Start the Rserve server
library("RSAP")
require("Rook")
setwd("C:/Blag/R_Scripts")
 
conn = RSAPConnect("sap.yml")
parms <- list('DELIMITER' = ';',
                 'FIELDS' = list(FIELDNAME = list('CARRID', 'CARRNAME')),
                 'QUERY_TABLE' = 'SCARR')
res<-RSAPInvoke(conn, "RFC_READ_TABLE", parms)
scarr<-res$DATA
flds<-sub("\\s+$", "", res$FIELDS$FIELDNAME)
scarr<-data.frame(colsplit(scarr$WA,";", names=flds))
 
parms<-list('DELIMITER' = ';',
               'FIELDS' = list(FIELDNAME = list('CITYFROM')),
               'QUERY_TABLE' = 'SPFLI')
res<-RSAPInvoke(conn, "RFC_READ_TABLE", parms)
spfli<-res$DATA
flds<-sub("\\s+$", "", res$FIELDS$FIELDNAME)
spfli<-data.frame(colsplit(spfli$WA,";", names=flds))
spfli<-unique(spfli)
 
get_data<-function(p_carrid,p_cityfrom){
  parms<-list('DELIMITER' = ';',
                 'FIELDS' = list(FIELDNAME = list('CITYTO','FLTIME')),
                 'OPTIONS' = list(TEXT = list(p_carrid, p_cityfrom)),
                 'QUERY_TABLE' = 'SPFLI')
  res<-RSAPInvoke(conn, "RFC_READ_TABLE", parms)
  RSAPClose(conn)
  spfli<-res$DATA
  flds<-sub("\\s+$", "", res$FIELDS$FIELDNAME)
  if(length(spfli$WA)>0){
  spfli<-data.frame(colsplit(spfli$WA,";", names=flds))
  return(spfli)
  }else{
   return(spfli)
  }
}
 
newapp<-function(env){
  req<-Rook::Request$new(env)
  res<-Rook::Response$new()
  res$write('<form method="POST">\n')
  res$write('<div align="center"><table><tr>') 
  res$write('<td>Select a carrier: <select name=CARRID>')
  for(i in 1:length(scarr$CARRID)) {
    res$write(sprintf('<OPTION VALUE=%s>%s</OPTION>',
                      scarr$CARRID[i],scarr$CARRNAME[i]))
  }
  res$write('</select></td><td>')
  res$write('Select a city: <select name=CITYFROM>')
  for(i in 1:length(spfli$CITYFROM)) {
    res$write(sprintf('<OPTION VALUE=%s>%s
                       </OPTION>',spfli$CITYFROM[i],spfli$CITYFROM[i]))
  }
  res$write('</select></td>')
  res$write('<td><input type="submit" name="Get Flights"></td>')
  res$write('</tr></table></div>')
  res$write('</form>')
 
  if (!is.null(req$POST())) {
    p_carrid = req$POST()[["CARRID"]]
    p_cityfrom = req$POST()[["CITYFROM"]]
    flights_from<-paste('Distance in Flights from ',p_cityfrom,sep='')
 
    p_carrid<-paste('CARRID = \'',p_carrid,'\'',sep='')
    p_cityfrom<-paste('AND CITYFROM =\'',p_cityfrom,'\'',sep='')
 
    spfli<-get_data(p_carrid,p_cityfrom)
 
    if(length(spfli$CITYTO) > 0){
    png("Flights.png",width=800,height=500)
    plot(spfli$FLTIME,type="n",axes=FALSE,ann=FALSE)
    lines(spfli$FLTIME,col="blue")
    points(spfli$FLTIME, pch=21, bg="lightcyan", cex=1.25)
    box()
    xy<-length(spfli$CITYTO)
    axis(2, col.axis="blue", las=1)
    axis(1, at=1:xy, lab=spfli$CITYTO, col.axis="purple")
    title(main=flights_from, col.main="red", font.main=4)
    dev.off()
    res$write("<div align='center'>")
    res$write(paste("<img src='", server$full_url("pic"), "/", 
                    "Flights.png'", "/>", sep = ""))
    res$write("</div>")
    }else{
      res$write("<p>No data to select...</p>")
    }
  }
  res$finish()
}
 
server = Rhttpd$new()
server$add(app = newapp, name = "Flights")
server$add(app = File$new("C:/Blag/R_Scripts"), name = "pic")
server$start()
server$browse("Flights")

Este es el resultado...





Como pueden ver, estamos leyendo data de SAP para llenar ambos SELECTs y luego hacer una consulta. Generamos un grafico PNG mostrando la distancia desde el City From al City To y luego llamando desde nuestro Web Page para mostrarlo en la pantalla.

Como pueden ver, RSAP nos da muchas oportunidades de las cuales podemos sacar ventaja simplemente poniendo un poco de esfuerzo e imaginacion. Espero que esto incentive su interes en R -;)

Saludos,

Blag.

No comments: