Swift Firebase data format - json

when I did asked firebase the following.
print("\(WarSerArray[CompanyData.companyName]!.allValues)")
print("keys\(WarSerArray[CompanyData.companyName]!.allKeys)")
it printed out this information.
[{
PhonNumber = 7607588500;
address = "2378 Primrose Ave. Vista, CA. 92083";
currentStoreArray = Headquarters;
email = "james#opportunitysoftware.com";
faxNumber = "";
key = "-KLSM8y0BDfs6B1jtsA5";
name = "Service Center 1";
}]
keys[-KLSM8y0BDfs6B1jtsA5]
[{
PhonNumber = 7607588500;
address = "2378 Primrose Ave. Vista, CA. 92083";
currentStoreArray = Headquarters;
email = "james#opportunitysoftware.com";
faxNumber = "";
key = "-KLSM8zu6AFKa7V0beCh";
name = "Warehouse 1";
}]
keys[-KLSM8zu6AFKa7V0beCh]
how do I get name?

var CompanyData = CompanyDataStruct()
struct CompanyDataStruct {
var key = ""
var webpage:String! = ""
var OwnerName:String! = ""
var address:String! = ""
var managerPNumber:String = ""
var dueOnOrder = 0.0
var email:String! = ""
var fax:String! = ""
var itemsOrderHistory:String! = ""
var companyName:String! = ""
var money = 0.0
var notes:String! = ""
var tax = 0.0
var pNumber:String = ""
var ManagerContact = ""
var opw:String! = ""
var mpw:String! = ""
var OwedToCompany = 0.0
var OwedString:String! = ""
var taxID:String! = ""
var reSalesID:String! = ""
var BoxCount = 0
var secondTicketID:String! = ""
var secondTicketNumber = 0
var useSecondTicketID = false
var printerSettings = ""
var quoteDays = 0
var fulfillmentPrinter = false
var fulfillmentEmail = false
var printBill = false
var emailBill = false
var system = false
var printReceipt = false
var emailReceipt = false
var theFulFillEmail = ""
var logoName = ""
var delivery = false
var ac1 = ""
var ac2 = ""
var ac3 = ""
var storeID = ""
var warehouse = ""
var serviceCenter = ""
var currentStore = ""
var StoreCount = 0
var WareHouseCount = 0
var ServiceCenterCount = 0
var MoneySymbol = ""
var refundLevel = 0
var shareBarcode = true
var LoGoImage = DefaultImage
}
var WarehouseData2 = WareServiceStruct()
struct WareServiceStruct {
var name = String()
var address = String()
var currentStoreArray = String()
var phoneNumber = String()
var faxNumber = String()
var email = String()
var key = String()
}
let WareSerRef = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ")
let WareSerRefName = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("name")
let WareSerRefAddress = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("address")
let WarSerRefCurrentStore = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("CurrentStore")
let WareSerRefPhone = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("PhoneNumber")
let WareSerRefFax = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("faxNumber")
let WareSerRefEmail = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("email")
let WareSerRefKey = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("key")
func WarehouseFirebaseSetter(sedner: WareServiceStruct) {
let key = WareSerRef.childByAutoId().key
WarehouseData2 = sedner
WarehouseData2.key = key
let WareToAdd = FBWarhouseData
let childUpdates = ["/Warehouse /\(CompanyData.companyName)/\(key)":WareToAdd]
WareSerRef.updateChildValues(childUpdates)
}
var FBWarhouseData = ["address" : WarehouseData2.address,"currentStoreArray" : WarehouseData2.currentStoreArray,"email" : WarehouseData2.email,"faxNumber" : WarehouseData2.faxNumber,"PhonNumber" : WarehouseData2.phoneNumber,"name" : WarehouseData2.name,"key" : WarehouseData2.key] as NSDictionary

Related

Using custom date format

I have this working script to sent mails with data from a Google sheet:
function SendEmail() {
let timestamp = 0
let poid = 1
let sku = 2
let qty = 3
let description = 4
let licenseid = 5
let itcost = 6
let total = 7
let company = 8
let contact = 9
let contactmail = 10
let endusermail = 11
let address = 12
let country = 13
let status = 14
let suppliermail = 15
let currency = 16
let otherinfo = 17
let brand = 18
let comment = 19
let cc = 20
let emailTemp = HtmlService.createTemplateFromFile("MAIL")
let ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA")
let sd = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA2")
let data = ws.getRange("A2:V" + ws.getLastRow()).getValues()
let sData = sd.getRange("B2:J" + sd.getLastRow()).getValues()
let sInfo = sData.map(function (r) { return r[0] })
data = data.filter(function (r) { return r[14] == 'SENTNOW' })
if (data.length) {
let found = false
data.forEach(function (row) {
emailTemp.ts = row[timestamp].toLocaleString("da-DK")
emailTemp.po = row[poid]
emailTemp.co = row[contact]
emailTemp.cm = row[company]
emailTemp.ad = row[address]
emailTemp.cu = row[country]
emailTemp.cn = row[contactmail]
emailTemp.sk = row[sku]
emailTemp.de = row[description]
emailTemp.qt = row[qty]
emailTemp.it = (row[itcost]).toLocaleString("da-DK")
emailTemp.to = (row[total]).toLocaleString("da-DK")
emailTemp.ce = row[comment]
emailTemp.cy = row[currency]
emailTemp.eu = row[endusermail]
emailTemp.li = row[licenseid]
emailTemp.ot = row[otherinfo]
let indexSupp = sInfo.indexOf(row[15])
if (indexSupp > -1) {
//only change status if supplierdata email is found
found = true
emailTemp.spname = sData[indexSupp][1]
emailTemp.saddress1 = sData[indexSupp][2]
emailTemp.saddress2 = sData[indexSupp][3]
emailTemp.scountry = sData[indexSupp][4]
emailTemp.sterms = sData[indexSupp][5]
emailTemp.scurrency = sData[indexSupp][6]
emailTemp.sothers = sData[indexSupp][7]
emailTemp.vat = sData[indexSupp][8] * 100
emailTemp.totvat = (row[total] * sData[indexSupp][8]).toLocaleString("da-DK")
emailTemp.totandvat = (row[total] + (row[total] * sData[indexSupp][8])).toLocaleString("da-DK")
let subjectLine = "Subject line # " + row[poid]
let htmlMessage = emailTemp.evaluate().getContent()
//only send email if supplierdata email is found
try {
GmailApp.sendEmail(
row[suppliermail],
subjectLine,
"",
{ name: 'Name', htmlBody: htmlMessage, bcc: 'myemail#domain.com' })
}
catch (err) {
SpreadsheetApp.getUi().alert(err)
}
}
})
if (found) {
let sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA")
.getRange('O2:O')
.createTextFinder('SENTNOW')
.replaceAllWith('SENT')
}
}
}
Only problem is the date format emailTemp.ts = row[timestamp].toLocaleString("da-DK")
This give output date-format "11.2.2022 06.00.00" within the e-mail sent to the reciever.
What I wish is the date to be just "02/11/2022"
I tried emailTemp.ts = row[timestamp].toLocaleString("da-DK").getDisplayValue() but that was not working.
Any suggestions ?
You're going to have to figure out your time zone but try this.
emailTemp.ts = Utilities.formatDate(row[timestamp],"GMT","dd/MM/yyyy");
Reference
Utilities.formatDate()

JDBC Connection from MySQL database to Spreadsheet very slow

I have created this script to push the data from my MySQL database to google spreadsheet.
Now, to be updated, I have created a trigger every 5 minutes to run the script, but strangely when I see the executions of the trigger, it run approximately every 40 minutes.
The run of the script is approximately 2 minutes and so after this it push the data in the spreadsheet.
Is there something wrong with the script?
And how can I enforce the update duration that I have established in the trigger?
var MAXROWS = 100000
var SEEKWELL_J_SHORT_DATES = { day: "yyyy-MM-dd", month: "yyyy-MM", year: "yyyy", dayNum: "dd", monthNum: "MM", yearNum: "yyyy", week: "W" }
var SEEKWELL_J_TIMEZONE = "UTC"
var HOST = 'xxx'
var PORT = 'xxx'
var USERNAME = 'xxx'
var PASSWORD = 'xxx'
var DATABASE = 'xxx'
var DB_TYPE = 'mysql'
function runSql(query, options) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
//var sheet = doc.getActiveSheet();
var sheet = doc.getSheets()[0];
var sheetName = sheet.getName();
//var cell = doc.getActiveSheet().getActiveCell();
var cell = sheet.getRange('a1');
var activeCellRow = cell.getRow();
var activeCellCol = cell.getColumn();
try {
var fullConnectionString = 'jdbc:' + DB_TYPE + '://' + HOST + ':' + PORT
var conn = Jdbc.getConnection(fullConnectionString, USERNAME, PASSWORD);
console.log('query :', query)
var stmt = conn.createStatement();
stmt.execute('USE ' + DATABASE);
var start = new Date();
var stmt = conn.createStatement();
stmt.setMaxRows(MAXROWS);
var rs = stmt.executeQuery(query);
} catch (e) {
console.log(e, e.lineNumber);
Browser.msgBox(e);
return false
}
var results = [];
cols = rs.getMetaData();
console.log("cols", cols)
var colNames = [];
var colTypes = {};
for (i = 1; i <= cols.getColumnCount(); i++) {
var colName = cols.getColumnLabel(i)
colTypes[colName] = { type: cols.getColumnTypeName(i), loc: i }
colNames.push(colName);
}
var rowCount = 1;
results.push(colNames);
while (rs.next()) {
curRow = rs.getMetaData();
rowData = [];
for (i = 1; i <= curRow.getColumnCount(); i++) {
rowData.push(rs.getString(i));
}
results.push(rowData);
rowCount++;
}
rs.close();
stmt.close();
conn.close();
console.log('results', results)
var colCount = results[0].length
var rowCount = results.length
var comment = "Updated on: " + (new Date()) + "\n" + "Query:\n" + query
if (options.omitColumnNames) {
results = results.slice(1)
rowCount -= 1
}
if (options.clearColumns && sheet.getLastRow() > 0) {
var startCellRange = sheet.getRange(startCell)
sheet.getRange(startCellRange.getRow(), startCellRange.getColumn(), sheet.getLastRow(), colCount).clearContent();
}
if (options.clearSheet) {
var startCellRange = sheet.getRange(startCell)
sheet.clear({ contentsOnly: true });
}
//sheet.getRange(activeCellRow, activeCellCol, rowCount, colCount).clearContent();
sheet.getRange(activeCellRow, activeCellCol, rowCount, colCount).setValues(results);
var cell = sheet.getRange(activeCellRow, activeCellCol)
cell.clearNote()
cell.setNote(comment);
sheet.setActiveRange(sheet.getRange(activeCellRow + rowCount + 1, activeCellCol))
console.log('query success!, rows = ', rowCount - 1)
}
function runSqlFromSheet() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sql = doc.getRange('query!A1').getDisplayValue();
var options = {}
Logger.log('sql;', sql)
runSql(sql, options)
}

Does my Google Apps Script in my Google Sheet have to request my data each time the Sheet opens?

I have a project that I've been working on which uses the Google Places API and pulls data about a specified place.
I am still learning about the functions of Google Cloud Platform as I quickly ran through my free $300 trial credit. I had hoped that my simple use case would not go through that all so quickly, but it appears that it made 62,000 requests in the one month that I used it.
I have noticed that every time I open my Google Sheet, while the Sheet has data in it already, it appears to re-request the data, presumably using up my allotted requests.
Is there a way to modify my code or a setting somewhere so that once data is pulled into the Sheet it does not have to pull it again unless I do so manually?
Or is my understanding of what's happening here mistaken? Should I be looking to fix this some other way?
As a side note, eventually I want to build in functionality so that I can use a custom UI button to trigger the scripts to run all over and change the color of the cell or something on ones where changes happened (eg. if business hours change, the cell turns yellow so I know to update my Google MyMap for that one detail. And then if I ran the function from the UI button again, that same hours cell would change to normal/no color fill as there had been no change since the last time the function was run), but I am not sure if this is the appropriate time to implement that change.
Below is my code:
// This location basis is used to narrow the search -- e.g. if you were
// building a sheet of bars in NYC, you would want to set it to coordinates
// in NYC.
// You can get this from the url of a Google Maps search.
const LOC_BASIS_LAT_LON = "43.17272951663479, 16.44381364713987"; // e.g. "37.7644856,-122.4472203"
function COMBINED2(text) {
var API_KEY = 'AIzaSyxxxxxxxxxxxxxxxxxxxxxxxxxrE';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeName = place.name;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
place.name,
place.formatted_address,
place.formatted_phone_number,
place.website,
place.url,
weekdays.trim(),
] ];
return data;
}
function GPS(text) {
//TEST PARSING
var API_KEY = 'AIxxxxyD1xxxxxxxxxxxxxxxxxxGKlrE';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var responseAPI = UrlFetchApp.fetch(queryUrl2);
var content = responseAPI.getContentText();
var json = JSON.parse(content.toString()); //Sample JSON parsing
//An array variable to contain the longitude and latitude data
var inputArray = [];
//Parse the "location" JSON array contents
var gpsCoord = json.result.geometry.location
//Place the JSON contents into the array variable
for (var j in gpsCoord){
inputArray.push([gpsCoord[j]]);
}
return inputArray.join(", ");
}
function name(text) {
var API_KEY = 'AIzaxxxxxxxxxxxxxxxxxxxxxrE';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeName = place.name;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
place.name
] ];
return data;
}
function address2(text) {
var API_KEY = 'AIzaxxxxxxxxxxxxxxxxxxxxxrE';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeName = place.name;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
place.formatted_address
] ];
return data;
}
function phone(text) {
var API_KEY = 'AIzxxxxxxxxxxxxxxxxxxxxxxxE';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeName = place.name;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
place.formatted_phone_number
] ];
return data;
}
function website(text) {
var API_KEY = 'AIzxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeName = place.name;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
place.website
] ];
return data;
}
function maps(text) {
var API_KEY = 'AIxxxxxxxxxxxxxxxxxxxxxxxxxrE';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeName = place.name;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
place.url
] ];
return data;
}
function hours(text) {
var API_KEY = 'AIzxxxxxxxxxxxxxxxxxxxxxxxxxE';
var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
var queryUrl = baseUrl + '?input=' + text + '&inputtype=textquery&key=' + API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
var response = UrlFetchApp.fetch(queryUrl);
var json = response.getContentText();
var placeId = JSON.parse(json);
var ID = placeId.candidates[0].place_id;
var fields = 'name,geometry,formatted_address,formatted_phone_number,website,url,types,opening_hours';
var baseUrl2 = 'https://maps.googleapis.com/maps/api/place/details/json?placeid=';
var queryUrl2 = baseUrl2 + ID + '&fields=' + fields + '&key='+ API_KEY + "&locationbias=point:" + LOC_BASIS_LAT_LON;
if (ID == '') {
return 'Give me a Google Places URL...';
}
var response2 = UrlFetchApp.fetch(queryUrl2);
var json2 = response2.getContentText();
var place = JSON.parse(json2).result;
var placeName = place.name;
var placeAddress = place.formatted_address;
var placePhoneNumber = place.formatted_phone_number;
var placeWebsite = place.website;
var placeURL = place.url;
var weekdays = '';
place.opening_hours.weekday_text.forEach((weekdayText) => {
weekdays += ( weekdayText + '\r\n' );
} );
var data = [ [
weekdays.trim(),
] ];
return data;
}

"Lock wait timeout exceeded" when sending data from Google Sheets to MySQL

I wrote an Apps Script macro to send data from a Google spreadsheet to a MySQL table. In a first time, in delete some rows in the table and then I add rows in this table. I sometimes get a "Lock wait timeout exceeded; try restarting transaction" error. Sometimes it runs after 100 seconds, sometimes 4 minutes.
I don't understand what is wrong with this code.
//classeur.insertSheet("feuillebis")
//feuillebis=classeur.getSheets()[1]
//var feuillebis=classeur.getSheetByName('feuillebis')
var classeur = SpreadsheetApp.getActiveSpreadsheet() ;
var feuille = classeur.getActiveSheet();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var nbrow = feuille.getMaxRows()
function Send_Weekly_Order_To_Data_Base() {
///here are all the connection parameters
var classeur = SpreadsheetApp.getActiveSpreadsheet();
var feuille = classeur.getActiveSheet();
var nbrow = feuille.getMaxRows();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
///get the weekly_order as an array from the sql
var rowcount = 0;
var stmt2 = conn.createStatement();
var results = stmt2.executeQuery("SELECT * FROM eatology.weekly_order");
while (results.next()) {
if (results.getInt(1) > rowcount){
rowcount = results.getInt(1)
}
}
conn.commit();
results.close();
stmt2.close();
///delete the rows from the current week where we are running the macro
var timezone1 = classeur.getSpreadsheetTimeZone();
var date1 = Utilities.formatDate(feuille.getRange(2, 2).getValue(), timezone1, "yyyy-MM-dd");
var date2 = Utilities.formatDate(feuille.getRange(2, 3).getValue(), timezone1, "yyyy-MM-dd");
var date3 = Utilities.formatDate(feuille.getRange(2, 4).getValue(), timezone1, "yyyy-MM-dd");
var date4 = Utilities.formatDate(feuille.getRange(2, 5).getValue(), timezone1, "yyyy-MM-dd");
var date5 = Utilities.formatDate(feuille.getRange(2, 6).getValue(), timezone1, "yyyy-MM-dd");
var date6 = Utilities.formatDate(feuille.getRange(2, 7).getValue(), timezone1, "yyyy-MM-dd");
///clear the table weekly-order in the database
var stmt1 = conn.createStatement();
var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 + "'" +" or `Date` = " + "'" + date2 + "'" +" or `Date` = " + "'" + date3 + "'" +" or `Date` = "+ "'" + date4 + "'" +" or `Date` = " + "'" + date5 + "'" +" or `Date` = "+ "'" + date6 + "'" );
//var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 +"'");
conn.commit();
stmt1.close();
conn.close();
rowcount = rowcount + 1;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
var stmt = conn.prepareStatement('INSERT INTO eatology.weekly_order '
+ '(`Uid`, `Date`, `MP`, `Cname`, `Pname`, `Breakfast`, `Snack1`, `Lunch`, `Snack2`, `Dinner`) values (?,?,?,?,?,?,?,?,?,?)');
var program_name_line = 0;
var array = feuille.getRange(1, 1, nbrow, 7).getValues();
for (var j = 1; j < 7; j = j + 1) {
var inside = 0;
var i = 1;
while (array[i][0] != "Total" && i < 1000) {
i = i + 1
var color = feuille.getRange(i + 1, j + 1).getBackgrounds()
var fi1 = array[i][0].toString();
var fij = array[i][j].toString();
var empty = (fij == "");
var already = 0;
var test11111 = (color != "#5d31ce");
var cas1 = ((empty == false) && (fi1 != "Total") && (inside == 0));
var cas2 = (color == "#5d31ce" && inside == 1);
var cas3 = (empty == false);
if ((fi1 != "Total") && (inside == 0) && color != "#5d31ce") {
program_name_line = i;
inside = 1;
if (empty == false) {
var Uid = rowcount;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0]);
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = list[0];
var Snack1 = list[1];
var Lunch = list[2];
var Snack2 = list[3];
var Dinner = list[4];
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount + 1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
else if (color == "#5d31ce" && inside == 1) {
inside = 0;
}
else if (empty == false && color != "#5d31ce") {
var Uid = rowcount ;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0].toString());
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = (list[0]);
var Snack1 = (list[1]);
var Lunch = (list[2]);
var Snack2 = (list[3]);
var Dinner = (list[4]);
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount+1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
}
stmt.executeBatch();
conn.commit();
stmt.close();
conn.close();
}
function meal(MP, Pname){
var result= [0, 0, 0, 0, 0]
//in order to know if we have two snacks or only one because if the programm has more than 1200 cal, there are two snacks, otherwise, only one snack
var two_snacks = 1
if (MP.indexOf("1200") > -1) {
two_snacks = 0
}
//if the program type is '3'
if (Pname.indexOf("3") > -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
result[4] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if the program type is '2'
if (Pname.indexOf("2") > -1 && Pname.indexOf("S") == -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if there is the B letter
if (Pname.indexOf("B") > -1) {
result[0] = 1;
}
//if there is the L letter
if (Pname.indexOf("L") > -1) {
result[2] = 1;
}
//if there is the D letter
if (Pname.indexOf("D") > -1) {
result[4] = 1;
}
//if there is the 2S letter
if (Pname.indexOf("2S") > -1) {
result[1] = 1;
result[3] = 1;
}
//if there is the 1S letter
if (Pname.indexOf("1S") > -1) {
result[1] = 1;
result[1] = 1;
}
return result
}

Property has value in View but appears as 0 in page

Currently I am trying to display a user's age but it appears as 0 in the page.
This is the View
<div class="col-xs-6 col-sm-4 overview-box">
<table class="table-responsive">
<tbody>
<tr>
<td class="overview-description-wrap">
<span class="overview-description">#translations["Player_Age"]</span>
</td>
<td class="overview-info hidden-xs" style="display:table-cell">
<span class="overview-info-lg">#Model.Age</span>
#if (Model.ShowDateOfBirth)
{
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
}
</td>
<td class="overview-info hidden-lg hidden-sm hidden-md">
<span class="overview-info-lg">#Model.Age</span>
<br />
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
</td>
</tr>
</tbody>
</table>
</div>
And this is the action that gets the values
public PlayerOverviewViewModel GetPlayerViewModel(int playerId, int sport, int country, int currentPlayerId = 0, int clubId = 0, string color = "")
{
PlayerOverviewViewModel result = new PlayerOverviewViewModel();
Nomenclatures.Sports currentsport = (Nomenclatures.Sports)sport;
Nomenclatures.Countries currentCountry = (Nomenclatures.Countries)country;
var state = LoadPlayerState(playerId, sport);
var finishedMatches = GetFinishedMatches(state, playerId, rankingId: 0).ToList();
var upcomingMatches = GetUpcomingMatches(state, playerId, currentPlayerId, 9).ToList();
var testMatches = ParseUpcomingChallenges(state, upcomingMatches);
var eventInvitations = new List<EventInvitationViewModel>();
var tournamentInvitations = GetTournamentInvitations(currentPlayerId);
var parsedInvitations = ParseTournamentInvitations(state, tournamentInvitations);
eventInvitations.AddRange(parsedInvitations);
var clubLeagueInvitations = GetClubLeagueInvitations(currentPlayerId);
parsedInvitations = ParseClubLeagueInvitations(state, clubLeagueInvitations);
eventInvitations.AddRange(parsedInvitations);
var playerRankings = state.PlayerRankings;
var rankingNames = _data.OrganisationRankings.GetRankingNames(playerRankings.Select(x => x.OrganisationRankingId.Value));
var player = state.CurrentPlayer;
int organizationId = state.CurrentPlayer.HomeClubId ?? 0;
var topRanking = GetPlayerRanking(state);
var playerCareerTopRanking = GetPlayerHighestStanding(state);
var playerCareerTopRankingDate = GetTopPlayerRankingDate(state);
var doubleCareerTopRanking = GetTopDoubleRanking(state, sport, country);
var doubleCareerTopRankingDate = GetTopDoubleRankingDate(state, sport, country);
var homeclub = player.Organisation ?? new Organisation();
var profileImg = _data.Images.PlayerImage(playerId);
var playerCareerWins = GetPlayerCareerWins(playerId, sport, state.Challenges);
var playerCurrentYearWins = GetPlayerCurrentYearWins(playerId, sport, state.Challenges);
var playerCareerLooses = GetPlayerCareerLooses(playerId, sport, state.Challenges);
var playerCurrentYearLosses = GetPlayerCurrentYearLooses(playerId, sport, state.Challenges);
var doublePlayerCurrentYearWins = GetDoublePlayerCurrentYearWins(playerId, sport);
var doublePlayerCareerLooses = GetDoublePlayerCareerLooses(state, sport);
var doubleCareerWins = GetDoubleCareerWins(state, sport);
var doublePlayerCurrentYearLooses = GetDoublePlayerCurrentYearLooses(state, sport);
var careerEventParticipations = GetAllEventsParticipations(playerId, sport, state.Challenges);
var currentYearEventParticipations = GetCurrentYearEventsParticipations(playerId, sport, state.Challenges);
var doubleCareerEventParticipations = GetDoubleCareerEventParticipations(state, sport);
var doubleCurrentYearEventParticipations = GetDoubleCurrentYearEventParticipations(state, sport);
var best3Wins = GetBest3Wins(state, playerId);
var singlePlayerHighestRankingCurrentYear = GetSinglePlayerHighestRankingForCurrentYear(state);
var doublePartnerInvitation = GetDoublePartnerInvitation(playerId);
//var playerUnavalability = this.GetPlayerSchedule(playerId);
string racquetName = player.GetRacket();
string shoesName = player.GetShoes();
result.Id = player.p_id;
result.Name = player.Name;
result.FirstName = player.FirstName;
result.MiddleName = player.MiddleName;
result.LastName = player.LastName;
result.Email = player.UserProfile.Email;
result.Address = player.PersonalInfo.pi_address;
result.BirthDate = player.PersonalInfo.pi_birth;
result.Age = DateHelper.GetAge(result.BirthDate);
result.Gender = player.PersonalInfo.pi_gender == 1 ? "Male" : "Female";
result.UserName = player.UserProfile.UserName;
result.Country = player.PersonalInfo.Country.Name;
result.CountryCode = player.PersonalInfo.Country.Short.ToLower();
result.RankingType = ((Nomenclatures.RankingTypes)topRanking.r_rankingtype).Description();
result.RankingClass = ((Nomenclatures.EventClasses)(topRanking.r_class ?? 1)).Description();
result.Points = topRanking.vPoints;
result.Level = topRanking.r_level ?? 1;
result.Standing = topRanking.vStanding;
result.HomeClub = string.IsNullOrEmpty(homeclub.Name) ? "No home club" : homeclub.Name;
result.ImageUrl = _manager.GetImageUrl(profileImg.img_id, Nomenclatures.ImageType.UserProfilePic);
result.ImageId = profileImg.img_id;
result.Racquet = racquetName;
result.Shoes = shoesName;
result.DominantHand = ((Nomenclatures.DominantHand)player.PersonalInfo.DominantHand).ToString();
result.BackHand = ((Nomenclatures.Backhand)player.PersonalInfo.Backhand).ToString();
result.Facebook = player.PersonalInfo.FacebookProfile;
result.Twitter = player.PersonalInfo.TwitterProfile;
result.WebSite = player.PersonalInfo.WebSite;
result.EmailVisible = player.PersonalInfo.pi_email_v;
result.ShowDateOfBirth = player.PersonalInfo.pi_birth_v || player.p_id == currentPlayerId;
//result.ScheduleDays = playerUnavalability.ScheduleDays;
//result.PlayerUnavalabilityVM = playerUnavalability;
result.PlayerCountryFlag = player.PersonalInfo.Country.Short.ToLower();
result.CareerWins = playerCareerWins;
result.GlobalEventsParticipatedSingles = careerEventParticipations;
result.EventsParticipatedSingles = currentYearEventParticipations;
result.CareerWinLossSingles = playerCareerWins + "-" + playerCareerLooses;
result.WinLossSingles = playerCurrentYearWins + "-" + playerCurrentYearLosses;
result.CareerWinLossDouble = doubleCareerWins + "-" + doublePlayerCareerLooses;
result.WinLossDoubles = doublePlayerCurrentYearWins + "-" + doublePlayerCurrentYearLooses;
result.GlobalEventsParticipatedDoubles = doubleCareerEventParticipations;
result.EventsParticipatedDoubles = doubleCurrentYearEventParticipations;
result.Best3Wins.Items = new List<ICarouselItem>(best3Wins);
result.CareerHighSingles = playerCareerTopRanking == 0 ? "-" : playerCareerTopRanking.ToString();
result.CareerHighDoubles = doubleCareerTopRanking == 0 ? "-" : doubleCareerTopRanking.ToString();
result.CareerHighDateSingles = playerCareerTopRankingDate;
result.CareerHighDateDoubles = doubleCareerTopRankingDate;
result.SinglesHighestRankingCurrentYear = singlePlayerHighestRankingCurrentYear == 0 ? "-" : singlePlayerHighestRankingCurrentYear.ToString();
result.DoublesHighestRankingCurrentYear = ""; //TODO: implement this
result.DoublePlayers = new List<DoublePartnersViewModel>();//TODO: implement this
result.PlayerRankings = playerRankings;
result.RankingNames = rankingNames;
result.CurrentSport = currentsport;
result.RankingCountry = currentCountry;
result.SportNumber = sport;
result.CountryNumber = country;
result.ParticipantType = (int)player.ParticipantType;
result.Class = player.p_class ?? 1;
result.DoubleInvitations = doublePartnerInvitation;
result.LastDonationDate = player.LastDonationDate;
int months;
int.TryParse(ConfigurationManager.AppSettings["donationPeriod"], out months);
result.IsDonated = player.LastDonationDate != null && player.LastDonationDate.Value.AddMonths(months) >= DateTime.UtcNow.Date;
var form = finishedMatches.OrderByDescending(x => x.Date).Take(5).Select(x => x.IsWon ? "W" : "L");
result.Form = form;
result.MatchesSection = new MatchesSectionVM
{
PlayerId = playerId,
CurrentPlayerId = currentPlayerId,
FinishedMatches = finishedMatches,
UpcomingMatches = testMatches,
UpcommingMatchesWatermark = !testMatches.Any(),
EventInvitations = eventInvitations,
FinishedMatchesWatermark = !finishedMatches.Any(),
LeftButtonName = "Confirm",
WatermarkMessage = "You dont have any matches to confirm. Create a challenge or join an event",
ShowButtons = currentPlayerId == playerId,
};
return result;
}
And this is the action that displays everything
[Authorize]
public ActionResult Index(int clubId = 0, string color = "")
{
if (mPlayerID == 0)
{
WebSecurity.Logout();
return RedirectToAction("login", "account", new { clubId, color });
}
var playerViewModel = _service.GetPlayerViewModel(mPlayerID, (int)mSport, (int)mCountry, mPlayerID, clubId, color);
playerViewModel.HasPhoto = _data.Images.PlayerHasPhoto(mPlayerID);
var profileCompletion = GetProfileCompletionPercents(playerViewModel);
playerViewModel.Id = mPlayerID;
playerViewModel.CurrentPlayerId = mPlayerID;
playerViewModel.DonationModel = new PayPalDonationModel(_data, mPlayerID);
playerViewModel.Languages = _cacheService.GetActiveLanguages();
ViewBag.ProfileCompletion = profileCompletion.Item1;
ViewBag.CompletionNext = profileCompletion.Item2;
return View(playerViewModel);
}
The only things that don't appear are the birth date and the user's age. Any suggestions ? Debugger shows that the properties have values in the View.