function fetchRecordingData(spreadsheet, specificBuyerName) {
var ringbaSheet = spreadsheet.getActiveSheet();
var dateValue = ringbaSheet.getRange("K1").getValue();
var targetDate = new Date(dateValue);
var startOfDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate(), 0, 0, 0);
var endOfDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate(), 23, 59, 59);
var reportStart = new Date(startOfDay.getTime());
var reportEnd = new Date(endOfDay.getTime());
var url = "
https://api.ringba.com/v2/{{account id}}/calllogs";
const apiToken = '###';
var extractedData = [];
var offset = 0;
var size = 1000;
while (true) {
var payload = {
"reportStart": reportStart, //Fri May 31 2024 00:00:00 GMT-0600 (Mountain Daylight Time)
"reportEnd": reportEnd, //Fri May 31 2024 23:59:59 GMT-0600 (Mountain Daylight Time)
"orderByColumns": [],
"filters": [],
"formatDateTime": true,
"formatPercentages": true,
"formatTimeZone": "America/Denver",
"formatTimespans": true,
"offset": offset,
"size": size,
"valueColumns": [
{ "column": "callDt" },
{ "column": "campaignName" },
{ "column": "publisherName" },
{ "column": "inboundPhoneNumber" },
{ "column": "buyer" }
]
};
var options = {
"method": "POST",
"headers": {
"Authorization": "Token " + apiToken,
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8"
},
"payload": JSON.stringify(payload),
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var jsonResponse = JSON.parse(response.getContentText());
var records = jsonResponse.report.records;
if (!records || records.length === 0) {
break;
}
var filteredData = records.filter(function(record) {
return record.buyer && record.buyer.toLowerCase().trim() === specificBuyerName.toLowerCase().trim();
}).map(function(record) {
return [
record.callDt,
record.campaignName,
record.buyer,
record.publisherName,
record.inboundPhoneNumber
];
});
extractedData = extractedData.concat(filteredData);
console.log(extractedData.length);
if (records.length < size) {
break;
}
offset += size;
}
if (extractedData.length > 0) {
var range = ringbaSheet.getRange("A2:E").clearContent();
ringbaSheet.getRange(ringbaSheet.getLastRow() + 1, 1, extractedData.length, extractedData[0].length).setValues(extractedData);
}
There are total of 831 records for that given date, when I run randomly it gives the correct number of records. However, when I run it 2-3 times in quick succession, the number of records in output keeps changing (825,837).
Then I wait for 5-10 minutes, run it, and it gives the correct output (831) again. I am unclear why doesn't it always give the same output. Any guidance to point out my mistake would be much appreciated.
0 comments:
Post a Comment
Thanks