LUA example: Create monthly summaries from operators’ timesheets

In this example we’ll build a document directly in the database. We’ll create one for each of our operators, with the hours worked in a given month. Given the kind of operation, this script is an action linked directly to the program.

Script Group
Program
Event
Program Action

We start by showing the form for choosing the parameters

output.clear()
finestra = program.newdataform()
finestra.settitle("Choose the month")

mesi = {"January","February","March","April","May","June","July","August",
"September","October","November","December"}

 
meseattuale = utility.datemonth(utility.getnow())
annoattuale = utility.dateyear(utility.getnow())
meseattuales = null
 

if meseattuale == 1 then meseattuales = "January" end
if meseattuale == 2 then meseattuales = "February" end
if meseattuale == 3 then meseattuales = "March" end
if meseattuale == 4 then meseattuales = "April" end
if meseattuale == 5 then meseattuales = "May" end
if meseattuale == 6 then meseattuales = "June" end
if meseattuale == 7 then meseattuales = "July" end
if meseattuale == 8 then meseattuales = "August" end
if meseattuale == 9 then meseattuales = "September" end
if meseattuale == 10 then meseattuales = "October" end
if meseattuale == 11 then meseattuales = "November" end
if meseattuale == 12 then meseattuales = "December" end


finestra.addfieldlist("Month","MESE",mesi,meseattuales)
finestra.addfieldinteger("Year","ANNO",annoattuale)
finestra.show()


if finestra.closewithx == true then
   do return end
end

--read the month and year chosen by the user
meseattuales = finestra.getvalue("MESE")
annoattuale = finestra.getvalue("ANNO")
for n,nomemese in pairs(mesi) do
   if nomemese == meseattuales then
      meseattuale = n
   end
end

First we create a dataform asking the user which month and year to analyze. For convenience, I set the current month and year as default values.

If the user closes the dataform with the X button, it’s good practice to stop the script.

tabella = database.getsql("SELECT * FROM segna_ore WHERE eli=0")

righe = tabella.getrows()
operatori = {}

for i = 1,tabella.countrows() do
   m = utility.datemonth(righe[i].getvalue("data"))
   y = utility.dateyear(righe[i].getvalue("data"))
   ope = righe[i].getvalue("gguid_operatore")
   if m == meseattuale and y == annoattuale then
      voto = false
      for i,operatore in pairs(operatori) do
         if operatore == ope then
            voto = true
         end
      end

      if voto == false then
         table.insert(operatori,ope)
      end
   end
end

Once we have the month and year to analyze, we go through the Segna_ore (timesheet) table to find which operators worked in that period. At this stage we only store the operator’s gguid, since we need it to search the tables. This also tells us how many documents we’re going to create.

for i,operatore in pairs(operatori) do

   nomeoperatore = ""
   tariffaoraria = 0
   toperatore = database.getsql("SELECT * FROM operatori WHERE gguid='" .. operatore .."' AND eli=0")

   if toperatore.countrows() > 0 then
      righeo = toperatore.getrows()
      nomeoperatore = righeo[1].getvalue("nome")
      tariffaoraria = righeo[1].getvalue("tariffa_oraria")
   end

We go through all the operators and, first of all, get each one’s name and hourly rate.

Note: the for loop is not closed here, because the following parts of the script still need to be added.

   if nomeoperatore ~= "" then

      --look for a monthly summary with the required characteristics

      gguidmese = ""
      totale_acconto = 0
      tme = database.getsql("SELECT * FROM mensili WHERE eli=0 and gguid_operatore='" ..operatore .. "' and mese='" .. meseattuales .. "' and anno=" .. tostring(annoattuale) .."")

      if tme.countrows() == 0 then
         --create a new record
         gguidmese = utility.gguid()
         
         stringa = "INSERT INTO mensili(gguid,tid,eli,arc,ut, uta,exp,gguidp,ind,tap,dsp,dsc,dsq1,dsq2,utc,tidc,gguid_operatore,operatore,mese,anno, tariffa_oraria,data) VALUES ("
         stringa = stringa .. "'" .. gguidmese .. "'," .. tostring(utility.tid()) .. ",0,0,'','','',''," ..tostring(database.getind("mensili")) .. ",'','','',0,0,'',0,'" ..operatore .. "','" .. utility.convap(nomeoperatore) .. "','" .. meseattuales .."'," ..tostring(annoattuale) .. "," ..tostring(tariffaoraria) .. ",#" .. utility.formatdate(utility.getnow(),"yyyy-MM-dd") .. "#)"

         database.setsql(stringa)

      else

         righe = tme.getrows()
         gguidmese = righe[1].getvalue("gguid")
         totale_acconto = righe[1].getvalue("totale_acconti")
         --delete the detail rows

         database.setsql("DELETE FROM mensili_rows WHERE gguidp='" .. gguidmese .. "'")

      end

We only consider operators with a valid name, then check whether a monthly summary already exists for that operator, month and year. If it doesn’t, we create it; otherwise we take the existing one and delete its rows, since we’ll recreate them.

Note the insert string, which lists all of Nios4’s system fields as well as the table’s own fields. Also remember that, to avoid malfunctions, every field must always be given a value, since the null condition is not handled.

Note: here too the initial if is not closed

      --start reading the timesheets

     tabella = database.getsql("SELECT * FROM segna_ore WHERE eli=0 and    gguid_operatore='" .. operatore .. "'")

      totaleore = 0
      righe = tabella.getrows()

      for i = 1,tabella.countrows() do
         m = utility.datemonth(righe[i].getvalue("data"))
         y = utility.dateyear(righe[i].getvalue("data"))
         ope = righe[i].getvalue("gguid_operatore")
         if m == meseattuale and y == annoattuale then

            --create the row and save it
            gguidr = utility.gguid()

            stringa = "INSERT INTO mensili_rows(gguid,tid,eli,arc,ut,uta,exp,gguidp,ind,tap,dsp,dsc,dsq1,dsq2,utc,tidc) VALUES ("
            stringa = stringa .. "'" .. gguidr .. "'," .. tostring(utility.tid()) .. ",0,0,'','','','" .. gguidmese .. "'," .. tostring(database.getind("mensili_rows")) .. ",'mensili','','',0,0,'',0)"

            database.setsql(stringa)

            --add the missing values

            stringa = "UPDATE mensili_rows SET data=#" .. utility.formatdate(righe[i].getvalue("data"),"yyyy-MM-dd") .. "#,"

            stringa = stringa .. "gguid_cliente='" ..   righe[i].getvalue("gguid_cliente") .. "', cliente='" .. utility.convap(righe[i].getvalue("cliente")) .. "',"

            stringa = stringa .. "totale_ore=" .. utility.convi(righe[i].getvalue("totale_ore")) .. ","

            stringa = stringa .. "lavori_effettuati='" .. utility.convap(righe[i].getvalue("lavori_effettuati")) .. "',"

            stringa = stringa .. "sede='" .. utility.convap(righe[i].getvalue("sede")) .. "'"

            stringa = stringa .. " WHERE gguid='" .. gguidr .. "'"

            database.setsql(stringa)

            totaleore = totaleore + righe[i].getvalue("totale_ore")

         end

      end

Now that we have created or retrieved the header of our monthly summary, we extract the timesheet rows for the operator. Here we run two write queries for convenience: the first creates the new row with the values the program needs, while the second fills in our own data.

      --update the monthly summary header
      totale_mensile = totaleore * tariffaoraria
      saldo = totale_mensile - totale_acconto

      stringa = "UPDATE mensili SET totale_mensile=" .. utility.convi(totale_mensile) .. ",totale_ore=" .. utility.convi(totaleore) .. ",saldo=".. utility.convi(saldo) .. " WHERE gguid='" .. gguidmese .."'"
      database.setsql(stringa)

   end

end

program.refreshsection("mensili")

After going through all the rows, we update the monthly summary header with the total amount and what we have already paid the operator.

We close the if condition on the operator’s name and the for loop.

Finally, we force the program to refresh the sections that use the mensili table, so the documents created are shown.