LUA example: Create customers from service reports

In this example we’ll see how to create customers starting from service reports. This is usually needed because technicians enter a new customer in the report without creating it through a subtable.

Script Group
Program
Event
Action

Another case is when the reports are imported from an Excel file created by another program, so the customers are not created. Of course, we assume that each report row holds the main data needed to identify the customer, whether it already exists or must be created.

table = database.getsql("SELECT * FROM reports WHERE eli=0")

rows = table.getrows()

for i = 1,table.countrows() do

--extrapolate the customer

namecustomer = rows[i].getvalue("namecustomer")

gguid_namecustomer = rows[i].getvalue("gguid_namecustomer")

--if gguid is empty the customer not exist

if gguid_namecustomer == "" then

--check if customer is already exist

tablecustomer = database.getsql("SELECT * FROM customers WHERE eli=0 and name='" .. utility.convap(namecustomer) .. "'")

if tablecustomer.countrows() == 0 then

--if 0 then customer not exist

--create a head customer

gguid_namecustomer = utility.gguid()

values = "INSERT INTO customers(gguid,tid,eli,arc,ut,uta,exp,gguidp,ind,tap,dsp,dsc,dsq1,dsq2,utc,tidc) VALUES ("

values = values .. "'" .. gguid_namecustomer .. "'," .. tostring(utility.tid()) .. ",0,0,'','','',''," .. tostring(database.getind("customers")) .. ",'','','',0,0,'',0)"

database.setsql(values)

--update data customers

values = "UPDATE customers SET name='" .. utility.convap(namecustomer) .. "',address='" .. utility.convap(rows[i].getvalue("address")) .. "' WHERE gguid='" .. gguid_namecustomer .. "'"

database.setsql(values)

database.addsyncbox("customers",gguid_namecustomer)

else

--customer already exist, update the gguid for create relation

rows2 = tablecustomer.getrows()

gguid_namecustomer = rows2[1].getvalue("gguid")

end

--update for syncbox windows

database.setsql("UPDATE reports SET tid=" .. tostring(utility.tid()).. ",gguid_namecustomer='" .. gguid_namecustomer .. "' WHERE gguid='" .. rows[i].getvalue("gguid") .. "'")

--add a syncbox for mobile

database.addsyncbox("reports",rows[i].getvalue("gguid"))

end

end

 

program.refreshsection("reports")

First we create the loop that reads the reports, considering only those without a valid linked customer gguid.

Since another report may already have created this customer, we first search for it by name.

If the name search finds nothing either, I create the customer using the data available in the report.

Then I update the report so it is linked to the customer through the customer’s gguid.

All of this works only if the customer on the report is handled with a subtable field.