In this example we’ll see how to create an invoice by retrieving the appointments carried out at a customer’s site, which can be seen as work reports.
Script Group
Form
Event
Action
The script is an action linked to the invoice form, so the workflow is: create a new invoice, choose the customer and run the script to extract the data.
if dataview.getvalue("gguid_nominativo") == "" then
dataview.showerror("Select a contact!")
do return end
end
First we check that a contact has been chosen, since without it we can’t find their appointments. If the special field linked to the Nominativo subtable is empty, we show an error message and exit the script.
finestra = program.newdataform()
finestra.addfielddate("Start date","DI",null)
finestra.addfielddate("End date","DF",null)
finestra.show()
if finestra.closewithx == true then
do return end
end
datainizio = finestra.getvalue("DI")
datafine = finestra.getvalue("DF")
We create a dataform asking the user which appointment dates to include in the invoice.
Note that if the user closes the dataform with the window’s X button, the script stops.
tabella= database.getsql("SELECT * FROM agenda WHERE gguid_nome_cliente='" .. dataview.getvalue("gguid_nominativo") .. "' AND eli=0")
Now we extract the data from the calendar, filtering it by contact. Remember this is just an example. We could have included the dates in the SQL string to get an already filtered table, but here we prefer to go through them all and keep only the appointments we need.
righe = tabella.getrows()
totaleore =0
for i=1,tabella.countrows() do
data = righe[i].getvalue("data")
if data >= datainizio and data <= datafine then
totaleore = totaleore +
righe[i].getvalue("ore_lavorate")
end
end
Now we go through all the rows and check that the date falls within the search range. Be careful with the date: written this way, it can easily extract no rows at all, because the dataform lets us pick a date without hours, minutes and seconds.
These values are set to 0, so if datainizio and datafine are the same, only appointments held exactly at midnight are retrieved. In this case the appointment has a field where the hours have already been calculated by another script. How you calculate the total time is up to you.
if totaleore == 0 then
dataview.showerror("No working hours found in the selected date range")
do return end
end
If nothing was found, we tell the user and exit the script.
vistagriglia = dataview.getatable("fatture_ca_rows")
riga = vistagriglia.adddatarow()
riga.setvalue("descrizione","Labour from " .. utility.datetostring(datainizio) .. " to " .. utility.datetostring(datafine))
riga.setvalue("qta",totaleore)
vistagriglia.update()
dataview.update()
Finally I create the row in the invoice grid and fill in the description and quantity. The price depends on how you manage it: it could be stored in the customer form, directly in the appointment, and so on.
