InDesign script to pull file by week number - javascript

I have a script for our newspaper that pulls comics from a folder and places them in an InDesign document. Most comics have the full date in the filename, but a few Sunday comics go by the week number for that Sunday. I.E. Blondie sunday filenames are like bln04ts.pdf or bln05ts.pdf. When we run the script we select the day to pull comics for but I'm unsure how to pull these files by week number?
Here is a sample by full date in filename if that helps at all.
` // LUANN
if (pageItem.label == "LUANN")
try{
name = "lu" + myDate.text + ".tif"
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(myFile);
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
name = "lu" + myDate.text + "_vacation.tif"
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(File(myFile));
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
name = "lu" + myDate.text + "_crx.tif"
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(File(myFile));
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
}catch(err){
//alert("caught error")
}`
Any ideas?

Well, if I understand you correctly you would need to add some lines like these to your script:
name = "bln" + myDate.week + "ts.pdf";
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(File(myFile));
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
However you'll also need to change the setup of you myDate object to include a week property. I don't know how the myDate object is set up (does it create the date text from the current date? Or from the file name of the document? Or something else?), so you would need to post a snippet of that, if you need further assistance on that step.

Related

Apps script.. i dont know how do i make Copy sheet`s Specific name

enter image description here
IF I PUSH THE BUTTON .
I WANT TO KNOW HOW CREATE NEW SHEET(COPY SHEET) NAMED NEXT + 1 DAY AND
THE CELL "C24" CONTENTS CHANGE TOO ?
BASIC SHEET NAME IS : 04/18/2022
I PUSH THE =BUTTON
NEW CREATE SHEET (ALL CONTENTS ARE COPY, BUT THE CELL "C24" DATE + 1 DAY
NEW CREATED SHEET`S NAME : 04/19/2022
This code help you to get the latest date form all sheet names and create a new name which is 1 day after the found sheet name.
// get all the sheet names of a spreadsheet and turn them into numbers, if the sheet name cannot be parsed into an int, make it a 0.
const sheetNames = SpreadsheetApp.getActiveSpreadsheet().getSheets()
.map(sheet => {
const name = parseInt(sheet.getName());
return isNaN(name) ? 0 : name;
});
// find the biggest numbers of all sheet names.
const maxDate = Math.max(...sheetNames)+'';
// create a date object with the found number.
const maxDateObj = new Date(`${maxDate.slice(0,4)}-${maxDate.slice(4,6)}-${maxDate.slice(6,8)}`);
// add 1 day on it.
const nextDateArr = JSON.stringify(new Date(maxDateObj.setDate(maxDateObj.getDate() + 1))).split(/"|-|T/g);
// format the date object into your sheet name format.
const nextDate = [nextDateArr[1],nextDateArr[2],nextDateArr[3]].join('');
console.log(nextDate);

How to get a timestamp based on a user's onclick event?

I'm creating an expense tracker application and wanted to get some insight on how to get and save a user's timestamp based on when they click the submit button.
let timestamp = new Date().getTime();
let todate = new Date(timestamp).getDate();
let tomonth = new Date(timestamp).getMonth() + 1;
let toyear = new Date(timestamp).getFullYear();
let original_date = tomonth + "/" + todate + "/" + toyear;
I understand the following code grabs the current date and formats it. If I were to just populate the DOM with original_date based on a click, then it'd work with today's date, but if I check it tomorrow, then it'll grab tomorrow's date. My current problem is, how would I go about saving the date based on a user's submit event without having it update to the current time.
Idea: Would having an event listener for the button be the way to go? Let's say:
function addTransaction(e) {
e.preventDefault();
let saveDate = original_date;
if (text.value.trim() === "" || amount.value.trim() === "") {
alert("Please add a description and amount of the transaction");
} else {
const transaction = {
id: generateID(),
text: text.value,
amount: +amount.value,
date: saveDate
};
transactions.push(transaction);
addTransactionDOM(transaction);
}
}
function addTransactionDOM(transaction) {
const sign = transaction.amount < 0 ? "-" : "+";
//creating new element
const item = document.createElement("li");
//Add class based on value
item.classList.add(transaction.amount < 0 ? "minus" : "plus");
item.innerHTML = `
${transaction.date}
${transaction.text}
${sign}${Math.abs(transaction.amount)}
`;
list.appendChild(item);
}
form.addEventListener("submit", addTransaction);
Would something like this work?
You can save in the browser localStorage the data you need to be retrieved later.
For example:
// Store data
localStorage.setItem('originalDateKey', original_date);
// Get data
var retrievedDate = localStorage.getItem('originalDateKey');
// Remove data
localStorage.removeItem('originalDateKey');
What you need is window.localStorage: localStorage documentation
window.localStorage.setItem(key, value) saves a string value to the user's local storage and can later be accessed with window.localStorage.getItem(key) where key is a unique string identifier.
Here's what I would do to achieve the desired result:
When the page is loaded, check if we have saved a previous date to localStorage
If saved date found, then load it from localStorage into the DOM
Set up a listener for the button which, saves the current date to localStorage (creating a new entry or overwriting the date that was there previously)
Here's some js flavored pseudo code:
// When site fully loaded, check for saved date and load into dom
window.addEventListener("load", function (event) {
const savedTimestamp = window.localStorage.getItem("savedDate");
// If savedTimestamp is null, then we have no previous saved date
if (savedTimestamp !== null) {
// Tip: we can reuse the date object instead of
// creating a new one every time here
const dateObj = new Date(savedTimestamp);
const todate = dateObj.getDate();
const tomonth = dateObj.getMonth() + 1;
const toyear = dateObj.getFullYear();
const savedDate = tomonth + "/" + todate + "/" + toyear;
// Show the saved date, just an example
// Put your code for showing the date here
showSavedDate(savedDate);
}
})
// ... rest of your code
function addTransaction(e) {
// ... omitting for brevity
let saveDate = original_date;
// ...
transactions.push(transaction);
addTransactionDOM(transaction);
// Save the current timestamp to local storage
window.localStorage.setItem("savedDate", saveDate);
}
// ... and so on
Make sure that saveDate is a string when you're saving it to localStorage, otherwise javascript will convert that to a string on its own and possibly screw things up.

How do you track timestamps with Appscript function and Importrange column

Currently, I'm trying to find a way to track the changes of various cell changes with individual time stamps. I want to track changes so that every time one of these rows changes it marks a new time stamp in another column. I need to it to track every time that some make a change with a new time stamp in a new column.
Do you think someone could help me?
This is the function I am using and I was just going to set up a trigger to go off every day. I'm not sure this is the best way to track this type of change either so I am open to other suggestions if anyone has any. The only think is that an onEdit function DOESN'T work when you are using importrange for values. I put an example of the work I'm using here: https://docs.google.com/spreadsheets/d/1PLmkEmJ6sMeu1Y-8mEJ5FaSNIXVnzEuYrilFNA7G0Pk/edit#gid=464181309
.js I was trying to use:
function checkCompleted() {
var s = SpreadsheetApp.getActive().getSheetByName('Sheet1');
s.getRange('G2:H').getValues()
.forEach (function (r, i) {
if(r[0] == 'Completed' && !r[1])
s.getRange(i + 2, 8).setValue(new Date())
})
}
Change tracking Log
The problem with tracking changes by just changing the time stamp is that you only have knowledge of the last change to a given line. So I would suggest just writing a short message into a log entry that you can come back and read anytime. This will include a time stamp, spreadsheet name, sheet name, range changed, oldvalue and new value. You will need to create a file. I use Drive Notepad to create the file and I put all of these sorts of files in one data folder and you'll need the id of the data folder. You'll also need the id of your spreadsheet and the name of the sheet you wish to log the edits of.
You'll need to create an onEdit trigger for the onEditLog function.
The Code:
function onEditLog(e)
{
var ss=e.source.openById('SpreadsheetId');
var docnam=ss.getname();
var shtnam=ss.getActiveSheet().getName();
var range=e.range.getA1Notation();
if(docnam=='Your Document Name' && shtnam=='Sheet1')
{
var msg= 'Spreadsheet: ' + docnam + ' Sheet: ' + shtnam + + 'Range: ' + range + ' has been changed from ' + e.oldvalue + ' to ' + e.value;
logEntry1(msg,'filename');
}
}
function logEntry1(entry,file)//not you cannot run this function like other functions from your script editor. It must be run from an onEdit trigger so that it has access to the event object.
{
var file = (typeof(file) != 'undefined')?file:'eventlog.txt';
var entry = (typeof(entry) != 'undefined')?entry:'No entry string provided.';
if(entry)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'hh:mm:ss a");
var s = ts + ' - ' + entry + '\n';
saveFile(s, file, true);
}
}
//this function is taken from myUtility library you'll need to add your own DefaultFileName and DataFolderID.
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;//make change here. It is a string so put quotes around it.
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;//make other change here. Again it is a string
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}

Windows Gadget reading specific information from Excel with Javascript

Hi I am trying to write a Windows Gadget that reads out information from an Excelsheet.
The Excelsheet entails a the dates, formated, of the whole year in column A2:A366 and the following columns are the names of the employes B1:Q1.
The gadget is to display the current day and who is marked absent. For each day a person is absent the cell is marked with an X.
I am not a Javascript programmer. And need help. I think I have the basic setup already, and I hope you can help me find my missings.
Explanation:
With the getToday function I am trying to get the date from the PC and format it to a string which I want to use to find in the Column A, which is set to be an array. The same function ist ment to give me back the right row in which it should look for the Xs. If it finds an X it is supposed to return the name of the column i.e the name of the employee.
function getToday (){
var today;
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
today = d.toString (day + "." + month + "." + year);
}
function refreshData(){
oExcel = new ActiveXObject('Excel.Application');
oWkBooks = oExcel.Workbooks.Open("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
oExcelSheet = oWkBooks.Worksheets();
oExcelSheet.Activate();
oExcel.ActiveWorkbook.RefreshAll();
oExcel.ActiveWorkbook.SaveAs("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
oWkBooks.Close();
location.reload();
}
function fetchData() {
function fetchData() {
$('#msg').html("Loading...");
$('#msg').show();
var oExcel;
var oExcelSheet;
var oWkBooks;
var cols;
oExcel = new ActiveXObject('Excel.Application');
oWkBooks = oExcel.Workbooks.Open("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
}
function findToday(stringArray){
for (var j=0; j<stringArray.length; j++) {
if (stringArray[j].match (var today) return cell;
return -1;
}
function returnAbwesentheit() {
var name = name.arr;
for (i=2;i<x.length;i==23) {
if ("cell"=="x") {
document.write (Name(cell));
else
return null;
}
}
::UPDATE::
I had a flash of inspiration. I think I am making this to difficult for myself. Maybe I could make excel do the finding of the date and who is absent. Then I would only generate the Outcome with Javascript into the Windows Gadget.

defining date in json file

I wonder to know how to set today's date in json file like we are using in js.
Is there any option to specify Date.today() in json file?
Because, json data has date object which specifies system date whenever we read the json file.
Hope, you will understand what i am trying to say.
Thanks in advance,
-Raja.
Server side can generate JSON dates in ISO format for example "2012-04-30T02:15:12.356Z"
Then client side can parse and load into date object
new Date(Date.parse("2012-04-30T02:15:12.356Z"))
JSON is a structured transport format. It does not have logic in it.
But here are options:
Why not just get the date when you read the file instead?
Have a server generate that JSON that includes the date at which it was generated. However, this is not ideal if you want the current date. By the time you read the file, the date generated by the server is already past.
build a parser that parses a string and make it search for custom markup.
For example, special markup is contained in #{}. Get the command inside, determine the command, and execute replacement.
var jsonString = '{"data1" : "foo","date" : "#{currentdate}"}'
In this case, I'll find #{currentdate}. I should create a function corresponding to this command to replace #{currentdate} into the current date during read (in the format you want)
var parsedString = jsonString.replace(/#\{(\w+)\}/g, function(match, group) {
if (group === 'currentdate') {
return new Date();
}
else if (group === 'anotherCommand') {
return 'anotherValue';
} //and so on
});
and the result is like this:
jsonString = '{"data1" : "foo","date" : "Fri May 04 2012 01:17:07 GMT-0700 (PDT)"}'
I suggest that you consider using the JSON-js (json2.js) parser, because it parses all standard JSON, but also allows you to add custom parse handling logic, called a reviver function, which fits your scenario very well. The basic syntax to invoke the JSON parser with a custom handler looks like this:
var myObject = JSON.parse(myJSONtext, reviverFunction);
Using your example input as a guide, it could be set up to work like this:
var jsonTxt = '[{' +
'"data1": "foo",' +
'"Date": "",' +
'"childs": [{' +
'"data2": "stack",' +
'"Date": ""' +
'}{}{}...]}]'; //and-on-and-on as in your comment
myData = JSON.parse(jsonTxt, function ( key, value ) {
if ( key === 'Date') { return new Date(); }
//any additonal custom logic you may need later...
});
A general introduction to JSON-js is provided at the JSON in JavaScript page, along with some brief intro info about JSON, and the page also includes some usage scenarios.
You can consider leveraging popular library like moment.js http://momentjs.com/
Then you can store date as YYYY-MM-DD in json and let moment handle the parsing:
var dateString = '2012-11-01';
var someday = moment(dateString);
var formattedDate = someday.format('ddd, DD MMM YYYY'); // 'Thu, 01 Nov 2012'
If you want to store the date, I would prefer to store as a String with a format like yyyy/mm/dd hh:mm:ss or something like that, and parse it in a Date object when I want to read it in the language I need.
obj = {
dates : ['2012/04/30 10:14:23', '2012/05/01 05:34:01']
}
I don't understand exactly what you want, with eval methods (it's an ugly practice), you can add a method to puts the actual date in object, and also adds himself at the children and call the method added in the children.
obj = {
data : "foo",
addDate : function() {
this.date = newDate();
if (this.children) {
for (var i = 0; i < this.children.length; i++) {
this.children[i].addDate = this.addDate;
this.children[i].addDate();
}
}
},
children : [{
data : "foo2"
}]
}
PS if you want to store it in a file, then you have to use the eval method (not recommended) storing the methods as a string or evry time you load the file do
jsonLoaded; // this var has the json that you store in a file;
var addDate = function() {
this.date = newDate();
if (this.children) {
for (var i = 0; i < this.children.length; i++) {
this.children[i].addDate = this.addDate;
this.children[i].addDate();
}
}
this.addDate = null; // remove the function we have added
// delete this.addDate; // if is compatible with browser
}
jsonLoaded.addDate = addDate;
jsonLoaded.addDate();
you cannot stringify json objects with functions, because of this, in the second method after add the method addDate, we remove that from the json object (also you can do delete this.addDate, but i don't know if it works in IE)
Wouldn't it be easier just to calculate the current system data whenever you read the file? I may be lacking context here but I don't see the point in storing that in the document.
If you really need to do so you can do as follows
var jsonObject = {"now":"new Date()"};
var date = eval(jsonObject.now);
it will be good to collect all the dates you want to transfer into a
Collection<String> dates = new ArrayList<String>();
Convert this collection to a json object and then at the receving end,convert it back to date. You can use joda date time API for conversions.
I use Gson in java to create json output, but Gson does not allow me to put javascript functions into the json. So this is what I do: Use replacement tags for the places you want to put code(like one of the earlier answers). Then get the text of the json, replace the tags, and then save the text to your json file:
Map<String, String> dynamicDates = new HashMap<>();
dynamicDates.put("d1", "new Date()");
dynamicDates.put("d2", "new Date(2015, 0, 1, 9, 30)");
dynamicDates.put("d3", "new Date(2015, 0, 1, 12, 30)");
JsonObject json = new JsonObject();
JsonObject root = new JsonObject();
JsonObject level_1_A = new JsonObject();
JsonObject level_1_B = new JsonObject();
json.add("root", root);
root.add("level_1_A", level_1_A);
root.add("level_1_B", level_1_B);
level_1_A.addProperty("d1", "${d1}");
level_1_A.addProperty("d2", "${d2}");
level_1_B.addProperty("d3", "${d3}");
StringBuilder sb = new StringBuilder();
new GsonBuilder().setPrettyPrinting().create().toJson(json, sb);
String str = sb.toString();
for (String key : dynamicDates.keySet()) {
str = str.replace("\"${" + key + "}\"", dynamicDates.get(key));
}
String jsonText = str;
String javascriptText = "var myJson = " + str + ";";
System.out.println(jsonText);
System.out.println(javascriptText);
So there is nothing left to be done on the consumption side in using this json. And the first output is:
{
"root": {
"level_1_A": {
"d1": new Date(),
"d2": new Date(2015, 0, 1, 9, 30)
},
"level_1_B": {
"d3": new Date(2015, 0, 1, 12, 30)
}
}
}
My use of json is usually saving it as javascript with an assignment, so this has been working for me.

Categories