This is the first time I have written a script myself as I have been self-learning over the past couple months. I am trying to build a script that will run when a record is created that creates repeated events. I have users who submit events through a form on the interface and added 3 fields focused on the workflow.
The flow I am hoping for is if someone checks off Repeating Event it will look at the Frequency field (single select) and the End On field (date) the workflow script will then create events with the same field values at the same times through the date specified in End On field. I know i could probably remove some of the script and use the conditions in the workflow but I have confused myself to the point of not knowing how to move forward without breaking anything more than it already is. Any hints or assistance would be greatly appreciated.
// Declare variables
let table = base.getTable("Table 1");
let currentRecord = //cannot figure out how to make it pull the current record that was created
let eventName = currentRecord.getCellValue("Event Name");
var calendar = currentRecord.getCellValue("Calendar to Publish");
var purpose = currentRecord.getCellValue("Purpose");
var category = currentRecord.getCellValue("Category");
var audience = currentRecord.getCellValue("Audience");
var startDate = currentRecord.getCellValue("Start Date");
var endTime = currentRecord.getCellValue("End Date");
var endDate = currentRecord.getCellValue("End On");
var frequency = currentRecord.getCellValue("Frequency");
// Check if the current record has a repeating event
if (currentRecord.getCellValue("Repeating Event")) {
// Calculate the number of days between the start and end dates
var numDays = (endDate - startDate) / (1000 * 3600 * 24);
// Calculate the number of times the event should be repeated
var numRepeats = 0;
switch (frequency) {
case "Annual":
numRepeats = Math.floor(numDays / 365);
break;
case "Semi-Annual":
numRepeats = Math.floor(numDays / 183);
break;
case "Quarterly":
numRepeats = Math.floor(numDays / 91);
break;
case "Monthly":
numRepeats = startDate.getMonth() + 1;
// numRepeats = Math.floor(numDays / 31); I tried the above because I thought that it would be more accurate given months with 30 days and also February
break;
case "Bi-Weekly":
numRepeats = Math.floor(numDays / 14);
break;
case "Weekly":
numRepeats = Math.floor(numDays / 7);
break;
default:
// If the frequency is not recognized, do not create any additional records
break;
}
// Create the duplicate records
for (var i = 0; i < numRepeats; i++) {
var newStartDate = new Date(startDate);
newStartDate.setDate(newStartDate.getDate() + (i + 1) * frequency);
var newEndDate = new Date(endTime);
newEndDate.setDate(newEndDate.getDate() + (i + 1) * frequency);
var newRecord = {
"Event Name": eventName,
"Calendar to Publish": calendar,
"Purpose": purpose,
"Category": category,
"Audience": audience,
"Start On": newStartDate,
"End On": newEndDate
};
table.createRecord(newRecord);
}
}