Schedule repetition frequency of a transaction or event based (daily, monthly or yearly). Kindly provide suggestions or feedbacks for improvements. Especially, I want to workout more edge case issues.
// Query for every record in “Table”
let table = base.getTable(“Table”);
let query = await table.selectRecordsAsync();
let srcDtl = await input.recordAsync(‘Select the row to repeat?’,table);
if (srcDtl) {
// Begin logic of creating repetitive transactions
// Replace ‘Field’ with name of the field in your table
let field = srcDtl.getCellValueAsString(‘Field’);
output.markdown("#### You selected “”+field+"" as the source budget");
// Display frequency options
let freq = await input.buttonsAsync('Frequency',u'Daily','Monthly','Yearly']);
// Replace 'Date' with date field in your table
let srcDate=new Date(srcDtl.getCellValue("Date"));
let nextDate = new Date(srcDtl.getCellValue("Date"));
let ctr=0;
// Obtain how many times the operation is to be repeated
let freqLen = await input.textAsync('How many times to repeat this?');
// Check if entered value is a number
if(!isNaN(parseInt(freqLen))) {
for(;ctr<=parseInt(freqLen)-1;ctr++) {
// Based on frequency type vary the next date
if(freq=='Daily') {
nextDate.setDate(nextDate.getDate()+1);
} else if(freq=='Monthly') {
if(nextDate==srcDate) {
nextDate.setMonth(srcDate.getMonth() +1);
} else {
// Set date to original date
nextDate.setDate(srcDate.getDate());
// Add a month
nextDate.setMonth(nextDate.getMonth() +1);
// Edge case: If date is not matched with src date, means month rolled over to next one
if(nextDate.getDate()!=srcDate.getDate()) {
// Edge case: Push back date one day before to roll back to last date of previous month
nextDate.setDate(nextDate.getDate()-1);
}
}
} else if(freq=='Yearly') {
nextDate.setFullYear(nextDate.getFullYear()+1);
}
// Insert records in 'Table'. Add any other fields that you want to copy in to the recurring record
await table.createRecordAsync({
"Field": field,
"Date":nextDate,
})
}
output.markdown('#### Inserted '+ctr+' records, *'+freq+'* starting from '+srcDtl.getCellValue("Date"));
} else {
// If entered value is NOT a valid number display error and end
output.markdown('#### Re-run this script and enter ONLY a number in the above field!');
}
// End logic of creating repetitive transactions
}