How to find and replace date, on timebased trigger by using ScriptApp Custom function - replace

I have a Google Document with only one date in the body of the document. I am trying to write a script that updates the date every 24 hours.
The date in the document is currently set to "11/01/2016" as text, 1 day less than today (12/01/2016). I assumed using a replaceText() would work.
This is my script at the moment.
ScriptApp.newTrigger("myFunction")
.timeBased()
.atHour(24)
.everyDays(1)
.inTimezone("GMT")
function myFunction()
{
var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyy");
var doc = DocumentApp.openById("ID of Document");
doc.replaceText(date-1,date) ;
}
What I am doing wrong here?

You can't replace text on document object, you need to get document body. your date is a string, you can't get yesterday by date-1. refer the date conversion too.
function myFunction()
{
var body = DocumentApp.getActiveDocument().getBody();
var d = new Date();
var yesterdayDate = Utilities.formatDate(new Date(d.getTime()-1*(24*3600*1000)), "GMT", "dd/MM/yyy");
var todayDate = Utilities.formatDate(d, "GMT", "dd/MM/yyy");
body.replaceText(yesterdayDate,todayDate) ;
}

Related

script.google.com error: TypeError: Cannot read property 'values' of undefined [duplicate]

This question already has answers here:
How can I test a trigger function in GAS?
(4 answers)
Closed 4 months ago.
I am trying to use a form submit to automatically complete a google doc template I have created. But I keep getting the error TypeError: Cannot read property 'values' of undefined, I am a complete newbie, can someone help me please?
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var timestamp = e.values[0];
var EmailAddress = e.values[1];
var CallReportWriter = e.values[2];
var DateOfMeeting = e.values[3];
var NameOfTheCustomerProspect = e.values[4];
var ContactNameFromClient = e.values[5];
var TitleandContacts = e.values[6];
var PresentfromSesomo = e.values[7];
var MeetingObjectives = e.values[8];
var MeetingResult = e.values[9];
var Background = e.values[10];
var Opportunities = e.values[11];
var Followuprequired = e.values[12];
var Responsible = e.values[13];
var Targetdates = e.values[14];
//file is the template file, and you get it by ID
var file = DriveApp.getFileById('12zJTxLgy_Nmxk1FScyZ3vqHzYnKQ55ckdQ8RsYy-MdA');
//We can make a copy of the template, name it, and optionally tell it what folder to live in
//file.makeCopy will return a Google Drive file object
var folder = DriveApp.getFolderById('1SorfCjOGknFVt1ch39MJ7atBorLf_Sdr')
var copy = file.makeCopy(DateOfMeeting + ',' + NameOfTheCustomer/Prospect, CallReport);
//Once we've got the new file created, we need to open it as a document by using its ID
var doc = DocumentApp.openById(copy.getId());
//Since everything we need to change is in the body, we need to get that
var body = doc.getBody();
//Then we call all of our replaceText methods
body.replaceText('{{MeetingDate}}', DateOfMeeting);
body.replaceText('{{NameOfCustomer}}', NameOfTheCustomer/Prospect);
body.replaceText('{{ReportWriterName}}', CallReportWriter);
body.replaceText('{{ContactNameFromClient}}', ContactNameFromClient);
body.replaceText('{{TitleAndContact}}', TitleandContacts);
body.replaceText('{{PresentFromSesomo}}', PresentfromSesomo);
body.replaceText('{{MeetingObjectives}}', MeetingObjectives);
body.replaceText('{{MeetingResults}}', MeetingResult);
body.replaceText('{{Background}}', Background);
body.replaceText('{{Opportunities}}', Opportunities);
body.replaceText('{{FollowUpRequired}}', Followuprequired);
body.replaceText('{{Responsible}}', Responsible);
body.replaceText('{{TargetDate}}', Targetdates);
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
}
Open the script editor of the sheet where the form response is landing
//
function onFormSubmit(e) {
var resp = e.source.getActiveSheet().getRange(e.range.rowStart,1, e.range.rowStart,14 ).getValues();
var timestamp = resp[0][0];
var EmailAddress = resp[0][1];
var CallReportWriter = resp[0][2];
var DateOfMeeting = resp[0][3];
// continue your code - I have not tested it
}
In script editor, you have to install the on-form-submit trigger
Then as soon as form response lands, your code will run and do whatever you want.

How to get current filters from PowerBi embedded export report

I am using powerbi embedded and I would like an export button similar to the one used on powerbi.com, that asks if you want to apply the current filters or not.
How can I get the current filters in javaScript in such a way that these can be passed to the back end, or to the javascript api to generate a PDF?
I am using the following code to generate the PDF currently, I just don't know how to get the current configuration current filters and current page selected in javaScript
public PowerBiExportViewModel CreateExport(Guid groupId,
Guid reportId,
IEnumerable<PowerBiReportPage> reportPages,
FileFormat fileFormat,
string urlFilter,
TimeSpan timeOut)
{
var errorMessage = string.Empty;
Stream stream = null;
var fileSuffix = string.Empty;
var securityToken = GetAccessToken();
using (var client = new PowerBIClient(new Uri(BaseAddress), new TokenCredentials(securityToken, "Bearer")))
{
var powerBiReportExportConfiguration = new PowerBIReportExportConfiguration
{
Settings = new ExportReportSettings
{
Locale = "en-gb",
IncludeHiddenPages = false
},
Pages = reportPages?.Select(pn => new ExportReportPage { PageName = pn.Name }).ToList(),
ReportLevelFilters = !string.IsNullOrEmpty(urlFilter) ? new List<ExportFilter>() { new ExportFilter(urlFilter) } : null,
};
var exportRequest = new ExportReportRequest
{
Format = fileFormat,
PowerBIReportConfiguration = powerBiReportExportConfiguration
};
var export = client.Reports.ExportToFileInGroupAsync(groupId, reportId, exportRequest).Result;
You can go to PowerBi playground and play around with their sample report. Next to "Embed" button you have "Interact" and option to get filters. In response you get JSON with filters. If you are too lazy to go there, here is the code it created for me
// Get a reference to the embedded report HTML element
var embedContainer = $('#embedContainer')[0];
// Get a reference to the embedded report.
report = powerbi.get(embedContainer);
// Get the filters applied to the report.
try {
const filters = await report.getFilters();
Log.log(filters);
}
catch (errors) {
Log.log(errors);
}

Expiring a Cookie after 30 days

I'm just need to make sure I have this correct. I don't have 30days (or even a day) to test this.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
I think all I have to do is add this line of code:
var days = "30";
Is this correct? How can I test that this works after 1 minute while still using the days var? I'm not very good at math :x
I can rest easy knowing everything is working.
I am testing every half-minute with the code below.
var days = "0.00034722222";

Google Apps Script document not accessible by replaceText()

Here is my code and I can't figure out why replaceText() isn't working.
function createDoc(){
var templateid = "1jM-6Qvy47gQ45u88WfDU_RvfuSTsw27zBP_9MfsUGr8"; // get template file id
var FOLDER_NAME = "Completed Rental Agreements"; // folder name of where to put doc
// get the data from an individual user
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = sheet.getRange(2, 1, sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
var lastRow = sheet.getLastRow();
var firstName = sheet.getRange(lastRow, 2, 1,1).getValues();
var lastName = sheet.getRange(lastRow, 3, 1,1).getValues();
var guestEmail = sheet.getRange(lastRow, 7, 1,1).getValues();
var companyEmail = "bearlakeprojectmanagement#yahoo.com";
var companyName = "Bear Lake Project Management";
var username = "jared.hislop.test#gmail.com"; // get their email (from sheet name)
var me = "jared.hislop.test#gmail.com";
//Copy Template
var docid = DocsList.getFileById(templateid).makeCopy("Rental Agreement - "+firstName+""+lastName+"-"+guestEmail).getId();
// var file = DocsList.getFileById(docid).addEditors(me);
// move file to right folder
var file = DocsList.getFileById(docid);
var folder = DocsList.getFolder(FOLDER_NAME);
file.addToFolder(folder);
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
var body_text = doc.addEditor("jared.hislop.test#gmail.com");
// Append Cabin Rules
// doc.appendParagraph("This is a typical paragraph.");
body.replaceText("/^companyEmail$/", "test");
body.replaceText("%companyName%", "test1");
body.replaceText("%todayDate%", "test1");
doc.saveAndClose();
}
I've tried doc.replaceText and body.replaceText along with several other options.
Any ideas why this isn't working?
Thank in advance
Consider this:
body.replaceText("%companyName%", "test1");
That will look for every instance of "companyName" with "%" on either side of it. The "%" in this case is just that, a piece of punctuation in a strange place. This is a convention used to decrease the likelihood of accidentally replacing real text in the document.
Your template document must have that exact pattern for the replacement to work. (Yours doesn't... instead you have just "companyName". Change it to "%companyName%".) Apply that rule for any other replacement you want to make.
You could benefit from some optimization.
...
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Next line is hard to maintain - there's a better way.
// var data = sheet.getRange(2, 1, sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
// Read whole spreadsheet, skip headers
var data = sheet.getDataRange().getValues().slice(1);
// Already read in all data, use it instead of reading sheet again.
var firstName = data[data.length-1][2-1]; // (2-1) because array counts from 0
var lastName = data[data.length-1][3-1]; // while spreadsheet columns from 1
var guestEmail = data[data.length-1][7-1]; // Better: put these into variables.
...
While experimenting with your code, I ran into an autocompletion issue with doc.getActiveSection(). It turns out that there has been a recent change, according to the release notes for April 15 2013.
Renamed Document.getActiveSection() to getBody().
You should update your code accordingly.

How to disable a date range in Jquery datepicker

I want to disable a range of dates which I are fetched using Ajax. I'm doing it as follows -
$("#date_frm").datepicker({
dateFormat: 'yy-mm-dd',
constrainInput: true,
beforeShow:function(input, inst) {
$.ajax({
type: "POST",
url: "/admin/get_time_span",
data: "",
success: function(data) {
disabled_day = data;
},
});
},
beforeShowDay: disableRangeOfDays
});
function disableRangeOfDays(d)
{
//var arr = "2012-04-19 to 2012-04-26,";
var arr = disabled_day.split(",");
var arr = arr.split(",");
var cnt = arr.length-1;
for(i=0; i<cnt; i++) {
arr1 = arr[i].split(" to ");
//create date for from_date
frm_dt = arr1[0].split('-');
//create date for to_date
to_dt = arr1[1].split('-');
if(d >= new Date(frm_dt[0],(frm_dt[1]-1),frm_dt[2]) &&
d <= new Date(to_dt[0],(to_dt[1]-1),to_dt[2])) {
return [false];
}
}
return [true,''];
}
This works but not for the first time. When I open the date picker first time, the date range still selectable. But, after I close and reopen it, the date range is disabled. Also, if I change the month and come back to the current month then also it works. How can I disable the date range for the first time I open the date picker ? Also, for each month, I want to fetch the date ranges and disable them. How can I do this ?
After spending much time in checking possibilities, I fetched all the date ranges only once while loading the page and assigned all to a hidden field. I removed the Ajax call and used the value of the hidden field directly in the function disableRangeOfDays(d) and it worked as expected.