const REQUEST_SHEET_NAME_ = 'Requests'; const REQUEST_HEADER_ = ['Request ID', 'Requester', 'Summary', 'Status']; const REQUEST_MAX_ROWS_ = 100; /** * Runs the request update from a time-driven trigger or manually. * * @returns {void} */ function runScheduledRequestUpdate() { const lock = LockService.getScriptLock(); if (!lock.tryLock(5000)) { Logger.log('Skipped request update because another execution is running.'); return; } try { const sheet = getRequestSheet_(); const values = readAndValidateRequests_(sheet); if (values.length === 1) { Logger.log('No request rows to update.'); return; } const statuses = values.slice(1).map(function (row) { return [row[3] === '' ? 'Ready' : row[3]]; }); const changed = statuses.filter(function (status, index) { return status[0] !== values[index + 1][3]; }).length; if (changed === 0) { Logger.log('No blank request statuses found.'); return; } sheet.getRange(2, 4, statuses.length, 1).setValues(statuses); SpreadsheetApp.flush(); Logger.log('Marked ' + changed + ' request(s) Ready.'); } finally { lock.releaseLock(); } } /** * @returns {SpreadsheetApp.Sheet} */ function getRequestSheet_() { const spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); if (!spreadsheet) { throw new Error('Open this project from its bound spreadsheet, not a standalone project.'); } const sheet = spreadsheet.getSheetByName(REQUEST_SHEET_NAME_); if (!sheet) { throw new Error('Requests sheet is missing. Import sample.csv into a sheet named Requests.'); } return sheet; } /** * @param {SpreadsheetApp.Sheet} sheet * @returns {Array>} */ function readAndValidateRequests_(sheet) { const range = sheet.getDataRange(); if (range.getNumRows() > REQUEST_MAX_ROWS_ + 1 || range.getNumColumns() > REQUEST_HEADER_.length) { throw new Error('Requests must fit within A1:D101 (100 request rows). Move other content to another tab.'); } const values = range.getValues(); const header = values[0]; if ( header.length !== REQUEST_HEADER_.length || header.some(function (value, index) { return value !== REQUEST_HEADER_[index]; }) ) { throw new Error('Requests must use this header row: Request ID, Requester, Summary, Status.'); } values.slice(1).forEach(function (row, index) { if (row.length !== REQUEST_HEADER_.length || !row[0] || !row[1] || !row[2]) { throw new Error('Request row ' + (index + 2) + ' is incomplete.'); } if (typeof row[3] === 'string' && row[3].startsWith('=')) { throw new Error('Request row ' + (index + 2) + ' has a Status value beginning with =.'); } }); if (values.length > 1) { const output = sheet.getRange(2, 4, values.length - 1, 1); if (output.isPartOfMerge()) { throw new Error('Status cells must not be merged.'); } if (output.getFormulas().some(function (row) { return row[0] !== ''; })) { throw new Error('Status cells must contain values, not formulas.'); } } return values; }