Return all Rows that meet Criteria - javascript

hy guys im learning google apps script to telegram bot,
i have write auto reply command and it success to reply, if i sent #02-02-2021 it will show all recorded data on that day, but on my code it just return only 1 row, i have trying anything but nothing work.
thanks for helping,
function searchDataByTanggalTransaksi(Tanggal){
var rangeNameTransaksi = "Transaksi!A2:O";
var rowsTransaksi = Sheets.Spreadsheets.Values.get(MYSSID, rangeNameTransaksi).values;
var panjangTransaksi = rowsTransaksi.length;
var Tanggal, Nama_Item, Divisi, Sat, Qty, Harga_Satuan, Debet, Kredit, Saldo, Peruntukan, Total = "";
var pesan ="";
for (var row = 0; row < panjangTransaksi; row++ ){
if ("#" + rowsTransaksi[row][1]==Tanggal){
Tanggal = "📅 Tanggal Transaksi : " + rowsTransaksi[row][1];
Nama_Item = rowsTransaksi[row][2];
Divisi = rowsTransaksi[row][3];
Sat = rowsTransaksi[row][4];
Qty = rowsTransaksi[row][5];
Harga_Satuan = rowsTransaksi[row][6];
Debet = rowsTransaksi[row][7];
Kredit = rowsTransaksi[row][8];
Saldo = rowsTransaksi[row][9];
Peruntukan = rowsTransaksi[row][12];
Total = "💸 Total Transaksi : " + rowsTransaksi[row][14] + ",-";
pesan += "<code>- " + Nama_Item + " |" + Qty + " " + Sat + " |" + Kredit + "</code>";
return pesan ;
}
}
return "Data tanggal tidak ditemukan";
}
function testgetRowsTransaksi(){
var tanggal = searchDataByTanggalTransaksi("#2");
var x = ""
}

One approach is to store found values in array, I assume that you want to return pesan right?
So solution one of possible solutions is that every record that is found you store it into array, and then return whole array(if nothing found array length will be 0).
Here is there modified code:
function searchDataByTanggalTransaksi(Tanggal) {
var rangeNameTransaksi = "Transaksi!A2:O";
var rowsTransaksi = Sheets.Spreadsheets.Values.get(MYSSID, rangeNameTransaksi)
.values;
var panjangTransaksi = rowsTransaksi.length;
var Tanggal,
Nama_Item,
Divisi,
Sat,
Qty,
Harga_Satuan,
Debet,
Kredit,
Saldo,
Peruntukan,
Total = "";
var pesan = "";
var resultArray = []; //Mentioned array to pass data in.
for (var row = 0; row < panjangTransaksi; row++) {
if ("#" + rowsTransaksi[row][1] == Tanggal) {
Tanggal = "📅 Tanggal Transaksi : " + rowsTransaksi[row][1];
Nama_Item = rowsTransaksi[row][2];
Divisi = rowsTransaksi[row][3];
Sat = rowsTransaksi[row][4];
Qty = rowsTransaksi[row][5];
Harga_Satuan = rowsTransaksi[row][6];
Debet = rowsTransaksi[row][7];
Kredit = rowsTransaksi[row][8];
Saldo = rowsTransaksi[row][9];
Peruntukan = rowsTransaksi[row][12];
Total = "💸 Total Transaksi : " + rowsTransaksi[row][14] + ",-";
pesan +=
"<code>- " +
Nama_Item +
" |" +
Qty +
" " +
Sat +
" |" +
Kredit +
"</code>";
return resultArray.push(pesan); //Data passed in per every iteration.
}
}
return resultArray; //returning line
return "Data tanggal tidak ditemukan"; // this line is obsolete
}
function testgetRowsTransaksi() {
var tanggal = searchDataByTanggalTransaksi("#2");
var x = "";
}

Though I'm not pretty sure, what kind of data panjangTransaksi variable holds, if you just want the all matching items in a concatenated string, you could try like below
function searchDataByTanggalTransaksi(Tanggal){
var rangeNameTransaksi = "Transaksi!A2:O";
var rowsTransaksi = Sheets.Spreadsheets.Values.get(MYSSID, rangeNameTransaksi).values;
var panjangTransaksi = rowsTransaksi.length;
return panjangTransaksi.reduce((acc, ele) => {
let Nama_Item, Divisi, Sat, Qty, Harga_Satuan, Debet, Kredit, Saldo, Peruntukan, Total = "";
if ("#" + ele[1] == Tanggal){
Tanggal = "📅 Tanggal Transaksi : " + ele[1];
Nama_Item = ele[2];
Divisi = ele[3];
Sat = ele[4];
Qty = ele[5];
Harga_Satuan = ele[6];
Debet = ele[7];
Kredit = ele[8];
Saldo = ele[9];
Peruntukan = ele[12];
Total = "💸 Total Transaksi : " + ele[14] + ",-";
acc += "<code>- " + Nama_Item + " |" + Qty + " " + Sat + " |" + Kredit + "</code>";
}
return acc;
}, '') || "Data tanggal tidak ditemukan";
}

The program will never enter this if ("#" + rowsTransaksi[row][1]==Tanggal) as Tanggal is undefined.

i have found the work around, on above method i was use return, but when i sendText it reply all the rows
case "/tgl" :
var ssIdLogistik ="mySsId";
var rangeNameTransaksi = "Transaksi!A2:O";
var rowsTransaksi = Sheets.Spreadsheets.Values.get(ssIdLogistik, rangeNameTransaksi).values;
var panjangTransaksi = rowsTransaksi.length;
var Tanggal, Nama_Item, Divisi, Sat, Qty, Harga_Satuan, Debet, Kredit, Saldo, Peruntukan, Total = "";
for ( var row = 0; row < panjangTransaksi; row++){
if (rowsTransaksi[row][1] == perintah[1]){
Tanggal = "📅 Tanggal Transaksi : " + rowsTransaksi[row][1];
Nama_Item = rowsTransaksi[row][2];
Divisi = rowsTransaksi[row][3];
Sat = rowsTransaksi[row][4];
Qty = rowsTransaksi[row][5];
Harga_Satuan = rowsTransaksi[row][6];
Debet = rowsTransaksi[row][7];
Kredit = rowsTransaksi[row][8];
Saldo = rowsTransaksi[row][9];
Peruntukan = rowsTransaksi[row][12];
Total = "💸 Total Transaksi : " + rowsTransaksi[row][14] + ",-";
text += "<code>- " + Nama_Item + " |" + Qty + " " + Sat + " |" + Kredit+ ",-" + "</code>\n";
}
}
if(text == ""){
text = "🚫 Periksa format penulisan kode permintaan Tanggal.\n\n" +
"Melihat transaksi berdasarkan tanggal di awali dengan '/tgl_' dengan format /tgl_hh-bb-tttt:\n" +
" 👉🏻 /tgl_02-02-2021 \n";}
sendText(updates.message.chat.id, logoData + "<code>" + Tanggal + "\n----------\n" + text + "----------\n" + Total + "</code>");
break;

Related

How to display today and 5 days with a counter and pass variables from build report down to the build alert function?

How to make "funding breakdown" show today and the next five business days without removing the “totalfunding” of just today and adding a counter to the “fundingbreakdown” so it comes out numbered?
I am passing through my variables from build report down to the build alert function, but for some reason, it is not passing the values from my variables. Why is that happening?
I appreciate your patience as this is my very first googleappscript.
function buildreport() {
const ss = SpreadsheetApp.getActive();
let data = ss.getSheetByName('February 2023').getRange("A:M").getValues();
var PrimorNonPrim = ss.getSheetByName('February 2023').getRange("A:A").getValues();
var Regionandentity = ss.getSheetByName('February 2023').getRange("B:B").getValues();
var Currency = ss.getSheetByName('February 2023').getRange("D:D").getValues();
var Amount = ss.getSheetByName('February 2023').getRange("F:F").getValues();
var RequestDate = ss.getSheetByName('February 2023').getRange("K:K").getValues();
var BankAcctCreditDate = ss.getSheetByName('February 2023').getRange("L:L").getValues();
var PayDate = ss.getSheetByName('February 2023').getRange("M:M").getValues();
let payload = buildAlert(data);
sendAlert(payload);
}
function buildAlert(data,PrimorNonPrim,Regionandentity,Currency,Amount,RequestDate,BankAcctCreditDate,PayDate) {
let today = new Date();
let filteredData = data.filter(row => {
let requestDate = new Date(row[10]);
return requestDate.getFullYear() === today.getFullYear() &&
requestDate.getMonth() === today.getMonth() &&
requestDate.getDate() === today.getDate();
});
let totalfunding = filteredData.reduce((total, row) => total + row[5], 0);
if (filteredData.length === 0) {
let fundingBreakdown = "Nothing coming up within 5 working days";
} else {
fundingBreakdown = (PrimorNonPrim + " " +"Entity" + " " + Regionandentity + " " + "Currency" + " " + Currency + " " + "Amount" + " " + Amount + " " + "Request Date" + " " + RequestDate + " " + "Bank Account Credit Date" + " " + BankAcctCreditDate + " " + "Pay Date" + " " + PayDate)}

Google Ads scripts - how to do customised or long rolling date ranges

I'm using the following script to export Google Ads data from my account, but I am stuck with Google's pre-set date ranges and can't figure out how/if it's possible to jimmy these. Ideal date range would be year to date, with the report refreshing each day and adding on a fresh day's data, but would also be interested if we can get all time to work.
I'm a coding novice, so apologies in advance.
Script:
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query);
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = currentSetting.ss + "<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
I've tried overwriting the data validation in the host spreadsheet, but think I need to amend the script itself also.

keep getting stuck in a loop

working on some word problems for my intro class and my html keeps getting stuck in a loop in the alert section of my code. once it goes in there it doesn't come back out no matter if I am inputting correctly. this is a beginner class so we have only just gotten into loops and switches so please keep it basic. thanks in advance!
var custOwed, numCust, dayTotal;
var woodTotal, alumTotal, steelTotal;
var rate;
var woodCount = 0;
var alumCount = 0;
var steelCount = 0;
var woodAccum = 0;
var alumAccum = 0;
var steelAccum = 0;
var anotherOrder = "yes";
var woodRate = 10;
var alumRate = 15;
var steelRate = 25;
var errorFlag = 0;
anotherOrder = prompt("Another Order", "yes or no");
while (anotherOrder == "yes") {
poleType = prompt("What type of pole would you like today?", "wood, aluminum, or steel");
numFeet = prompt("How many feet?", "10");
numFeet = parseInt(numFeet);
switch (poleType) {
case "wood":
woodCount = woodCount + 1;
woodAccum = woodAccum + numFeet;
rate = woodRate;
break;
case "aluminum":
alumCount = alumCount + 1;
alumAccum = alumAccum + numFeet;
rate = alumRate;
break;
case "steel":
steelCount = steelCount + 1;
steelAccum = steelAccum + numFeet;
rate = steelRate;
break;
default:
errorFlag = 1;
break;
}
if (errorFlag == 1) {
alert("You typed " + poleType + " the only choices were wood, aluminum, or steel");
anotherOrder = "yes";
} else {
custOwed = numFeet * rate;
alert("You Owe" + custOwed);
anotherOrder = prompt("Another Customer?", "yes or no");
}
}
numCust = woodCount + alumCount + steelCount;
woodTotal = woodAccum * woodRate;
alumTotal = alumAccum * alumRate
steelTotal = steelAccum * steelRate
dayTotal = woodTotal + alumTotal + steelTotal;
document.write("Number of Customers: " + numCust);
document.write("<br>Wood Customers: " + woodCount);
document.write("<br>Total Feet of Wood: " + woodAccum);
document.write("<br>Total owed of Wood: $" + woodTotal.toFixed(2));
document.write("<br>Aluminum Customers: " + alumCount);
document.write("<br>Total Feet of Aluminum: " + alumAccum);
document.write("<br>Total owed of Aluminum: $" + alumTotal.toFixed(2));
document.write("<br>Steel Customers: " + alumCount);
document.write("<br>Total Feet of Steel: " + alumAccum);
document.write("<br>Total owed of Steel: $" + alumTotal.toFixed(2));
document.write("<br>Total owed from the day: $" + dayTotal.toFixed(2));

I cant solve this: to find the minimum number from an array that is input through prompt()

I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:
<script>
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
return marks;
}
var studentMarks = getMarks();
var arrayLength = studentMarks.length;
var studentNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
studentNumber = (i + 1);
msg += 'student ' + studentNumber + ': ';
msg += studentMarks[i] + '%' + '<br />';
} document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>
I will do that in the following way:
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
return marks.split(',').map(n => Number(n));
}
var marksArray = getMarks();
var studentMarks = Math.min(...marksArray);
var position = marksArray.indexOf(studentMarks);
var msg = 'Student ' + Number(position + 1) + ': ';
document.getElementById('marks').innerHTML = msg + studentMarks + '%';
<p id="marks"></p>

While loop + switch

I can't figure this out I keep getting stuck in a loop. I don't know if I have my calculation or if statements in the right areas, please I could use some help. My output is like a end of day report. I could really use the help.
<script type="text/javascript">
<!--
// assignments
var cost, nachosCounter, moneyCollected, nachosRate, corndogRate, hotdogRate;
var hamAccum, hotdogAccum, corndogAccum, nachosAccum, hamburgerRate;
var beginDay, orderType, hamCounter, hotdogCounter, corndogCounter;
var totalHotdog, totalNachos, totalCorndog, totalHamburger, moneyCollected;
var hamburgerRate = 4;
var hotDogRate = 2;
var cornDogRate = 3;
var nachosRate = 5;
var hamCounter = 0;
var hotdogCounter = 0;
var corndogCounter = 0;
var nachosCounter = 0;
var beginDay = "yes"
//initalizing loop
beginDay = "yes"
//start loop
while (beginDay == "yes")
{
orderType = prompt("hamburger, hotdog, corndog, nachos", "");
if (orderType == "hamburger")
{
hamCounter = hamCounter + 1;
if (hamCounter == 1)
{
hamAccum = "<br>The total number of hamburgers purchased: " + hamCounter;
}
else
{
hamAccum = hamAccum + "<br>" + hamCounter;
}
}
else if (orderType == "hotdog")
{
hotdogCounter = hotdogCounter + 1;
if (hotdogCounter == 1)
{
hotdogAccum = "The total number of hotdog purchased:<br>" + hotdogCounter;
}
else
{
hotdogAccum = hotdogAccum + "<br>" + hotdogCounter;
}
}
if (orderType == "corndog")
{
corndogCounter = corndogCounter + 1;
if (corndogCounter == 1)
{
corndogAccum = "<br>The total number of corndogs purchased: <br>" + corndogCounter;
}
else
{
corndogAccum = corndogAccum + "<br>" + corndogCounter;
}
}
if (orderType == "nachos")
{
nachosCounter = nachosCounter + 1;
if (nachosCounter == 1)
{
nachosAccum = "<br>The total number of nachos purchased: <br>" + nachosCounter;
}
else
{
nachosAccum = nachosAccum + "<br>" + nachosCounter;
}
}
totalHotdog = hotdogCounter*hotDogRate;
totalHamburger = hamCounter*hamburgerRate;
totalCorndog = corndogCounter*cornDogRate;
totalNachos = nachosCounter*nachosRate;
moneyCollected = totalNachos+totalCorndog+totalHamburger+totalHotdog;
beginDay = prompt("More to add?", "yes");
}
//output
document.write(hotdogAccum);
document.write(hamAccum);
document.write(corndogAccum);
document.write(nachosAccum);
document.write("<br>The total dollar amount for hotdog: $ " + totalHotdog);
document.write("<br>The total dollar amount for hamburger: $ " + totalHamburger);
document.write("<br>The total dollar amount for corndogs: $" + totalCorndog);
document.write("<br>The total dollar amount for nachos: $" + totalNachos);
document.write("The total amount of money collected: $" + moneyCollected);
// -->
</script>

Categories