I have a script that is activated from a menu in a Google Doc. It brings up a prompt to enter in the name of a new doc that will be copied/created from a template. From there, I want this new doc to be moved to the proper year and quarter folder depending on today's date. So if the doc is created on December 23, the file would be moved to the Q4 folder within the 2022 folder.
So the folder structure looks like:
Projects/<year>/<quarter>
Ideally, I want the code that moves the file to the proper folder to fit within a variable called "newFolder." Below is the whole script that I have currently. Any ideas?
function onOpen() {
DocumentApp.getUi()
.createMenu("START")
.addItem("Create New Doc", "createDoc")
.addToUi();
}
function copyDoc() {
var ui = DocumentApp.getUi();
var response = ui.prompt("Name of Doc:", ui.ButtonSet.OK_CANCEL);
var button = response.getSelectedButton();
if (button == ui.Button.OK) {
var docName = response.getResponseText();
var templateId = "XXXXX";
var newFolder = // FOLDER THAT THE FILE SHOULD BE MOVED TO, DEPENDING ON TODAY'S DATE
DriveApp.getFileById(templateId).makeCopy(docName, newFolder);
}
}
CodePudding user response:
Are you looking for a snippet like this?
var date = "23/12/2022"
var month = date.split("/")[1]
var quarter = parseInt(month/4) 1
var year = date.split("/")[2]
var folder = `Projects/${year}/${quarter}`
Note: I didn't check the rest of your code, focused on the missing piece.
CodePudding user response:
You would want to define the Project
folder by ID (found in the URL) in case something similar appeared and since that wouldn't be expected to change. Swap that out in the below code and it should find the appropriate folder to dump the file in your makeCopy
line.
function getDatedFolder() {
const myProjectID = "????????????????????"; // Find this in the URL of your project folder
var newDate = new Date();
var aYear = newDate.getFullYear();
var aMonth = newDate.getMonth() 1;
var aQuarter = 'Q' Math.ceil(aMonth / 3);
var projectFolder = DriveApp.getFolderById(myProjectID);
var yearFolder = getSubFolder_(projectFolder, aYear);
var quarterFolder = getSubFolder_(yearFolder, aQuarter);
return quarterFolder;
}
function getSubFolder_(parentFolder, exactName) {
var someChildrenFolders = parentFolder.getFolders();
while (someChildrenFolders.hasNext()) {
var oneFolder = someChildrenFolders.next();
if (oneFolder.getName() == exactName) {
return oneFolder;
}
}
}