LUA example: Create a cost history for items

In this example I’ll show how to create a cost history for purchased items, so that you can analyze how the cost of each item changes over time.

Script Group
Form
Event
Post-save

This script can be added to the post-save event of the item. Remember to change or create the fields that differ from your database, and to create the Costiarticoli table.

tabellacosti = database.getsql("SELECT * FROM costiarticoli WHERE gguidp='" .. dataview.getvalue("gguid") .. "' ORDER by data DESC")

First we create a Tabellacosti object by retrieving all the rows from Costiarticoli, checking that the value of the gguidp field matches the gguid of the current item.

You could also look for all the rows with the same item code as the current one, depending on how your tables are built. However, if you ever change the code, the link to the costs is lost. Using the gguid instead ensures that the cost history is kept even if all the item’s data changes.

Note that the SQL string sorts the cost rows in descending order, so we can be sure that the first row is the last cost saved.

voto = false

nr = tabellacosti.countrows()

righe = tabellacosti.getrows()

We create a Voto variable that we’ll use to check whether the item cost needs to be saved. Then we get the number of rows and the rows themselves from Tabellacosti.

if nr == 0 then
   voto = true
else
   --check the current values
   costo = righe[1].getvalue("costo")
   if costo ~= dataview.getvalue("costo") then
      voto = true
   end
end

If the number of rows is zero, meaning no costs have ever been saved, we set the Voto variable to true.

If there are rows, we take the cost from the first row, which holds the last value saved, since the rows are sorted in descending order.

If that cost is different from the item’s current cost, we set the Voto variable to true.

if voto == true then
   grigliacosti = dataview.getatable("costiarticoli")
   riga = grigliacosti.adddatarow()
   riga.setvalue("gguidp",dataview.getvalue("gguid"))
   riga.setvalue("data",utility.getnow())
   riga.setvalue("ind",database.getind("costiarticoli"))
   riga.setvalue("costo",dataview.getvalue("costo"))
   riga.save()
end

If Voto is true, we save the values. First we add a new row to Grigliacosti, the additional table inside the item form. Then we set the gguidp to the item’s gguid so it can be found at the next search, and set the current date, the row index and the cost value. Finally we save the row.

Since we used gguidp to keep the relationship, the Costiarticoli table can be used as an additional table, so the item form shows its full cost history.