function onFormSubmit(e) {
try {
Logger.log("Form submitted. Triggered script.");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = sheet.getLastRow();
var values = sheet.getRange(lastRow, 1, 1, sheet.getLastColumn()).getValues()[0];
Logger.log("Form values: " + values);
var templateDocId = "1TN0Xi0Xy8GimyrVZBNubUy-7ZNF7FWvF9ECEakYEOqc";
Logger.log("Template document ID: " + templateDocId);
var columnGValue = values[6] || "Untitled";
var columnEValue = values[4] || "NoValue";
var formattedDate = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM-dd-yyyy");
var newFileName = columnEValue + " " + columnGValue + " " + formattedDate;
Logger.log("New file name: " + newFileName);
var templateFile = DriveApp.getFileById(templateDocId);
var newFile = templateFile.makeCopy(newFileName);
Logger.log("New file created: " + newFile.getName());
var newDoc = DocumentApp.openById(newFile.getId());
var body = newDoc.getBody();
// Replace placeholders within tables
replacePlaceholdersInTables(body, values);
replacePlaceholdersWithLinks(body, values);
// Remove rows where column 1 has content but column 2 is empty
removeEmptySecondColumnRows(body);
newDoc.saveAndClose();
// Write the hyperlink to column E
var docUrl = newFile.getUrl();
Logger.log("Writing hyperlink to column E: " + docUrl);
var columnE = 5; // Column E (1-based index)
var cell = sheet.getRange(lastRow, columnE);
var existingText = cell.getValue(); // Get current text in column E
if (existingText) {
var richText = SpreadsheetApp.newRichTextValue()
.setText(existingText) // Keep the existing text
.setLinkUrl(docUrl)
.build();
cell.setRichTextValue(richText);
Logger.log("Hyperlink successfully added to column E.");
} else {
Logger.log("No existing text in column E, hyperlink not applied.");
}
// Copy row to another sheet based on column C value
var columnCValue = values[2]; // Column C (0-based index)
if (columnCValue) {
var targetSheet = sheet.getParent().getSheetByName(columnCValue);
if (targetSheet) {
var newRow = targetSheet.getLastRow() + 1;
// Copy raw values first
targetSheet.appendRow(values);
// Get hyperlink from column E in the original row
var sourceCell = sheet.getRange(lastRow, columnE);
var richTextValue = sourceCell.getRichTextValue();
if (richTextValue) {
var targetCell = targetSheet.getRange(newRow, columnE);
targetCell.setRichTextValue(richTextValue);
Logger.log("Hyperlink successfully copied to " + columnCValue);
}
} else {
Logger.log("Target sheet not found: " + columnCValue);
}
}
} catch (err) {
Logger.log("An error occurred: " + err.message);
}
}
/**
* Function to replace placeholders within tables
*/
function replacePlaceholdersInTables(body, values) {
var tables = body.getTables();
if (tables.length === 0) return;
tables.forEach(table => {
var numRows = table.getNumRows();
for (var i = 0; i < numRows; i++) {
var numCols = table.getRow(i).getNumCells();
for (var j = 0; j < numCols; j++) {
var cell = table.getRow(i).getCell(j);
var text = cell.getText();
if (text.trim() !== "") { // Only process non-empty cells
text = text.replace(/\{\{Proposed effective term\}\}\s*/g, values[6] || "");
text = text.replace(/\{\{Number\/name\}\}\s*/g, values[4] || "");
text = text.replace(/\{\{College\/unit\}\}\s*/g, values[2] || "");
text = text.replace(/\{\{Colleges impacted\}\}\s*/g, values[7] || "");
text = text.replace(/\{\{Type\}\}\s*/g, values[8] || "");
text = text.replace(/\{\{New course name\}\}\s*/g, values[9] || "");
text = text.replace(/\{\{Lib Ed yes\/no\}\}\s*/g, values[12] || "");
text = text.replace(/\{\{Topic title\}\}\s*/g, values[13] || "");
text = text.replace(/\{\{Term previously offered\}\}\s*/g, values[14] || "");
text = text.replace(/\{\{Changes since offering\}\}\s*/g, values[15] || "");
text = text.replace(/\{\{Name to inactivate\}\}\s*/g, values[22] || "");
text = text.replace(/\{\{Program changes needed\}\}\s*/g, values[23] || "");
text = text.replace(/\{\{Name to reactivate\}\}\s*/g, values[24] || "");
text = text.replace(/\{\{Term last active\}\}\s*/g, values[25] || "");
text = text.replace(/\{\{Retain Lib Ed\}\}\s*/g, values[26] || "");
text = text.replace(/\{\{Other updates\}\}\s*/g, values[28] || "");
text = text.replace(/\{\{Current course name\}\}\s*/g, values[16] || "");
text = text.replace(/\{\{Description changes\}\}\s*/g, values[17] || "");
text = text.replace(/\{\{Summary of changes\}\}\s*/g, values[18] || "");
text = text.replace(/\{\{Rationale\}\}\s*/g, values[19] || "");
text = text.replace(/\{\{Lib Ed yes\/no 2\}\}\s*/g, values[21] || "");
text = text.replace(/\{\{BOR types of changes\}\}\s*/g, values[31] || "");
cell.setText(text);
}
}
}
});
}
/**
* Function to replace placeholders within tables with hyperlinks
*/
function replacePlaceholdersWithLinks(body, values) {
var tables = body.getTables();
if (tables.length === 0) return;
tables.forEach(table => {
var numRows = table.getNumRows();
for (var i = 0; i < numRows; i++) {
var numCols = table.getRow(i).getNumCells();
for (var j = 0; j < numCols; j++) {
var cell = table.getRow(i).getCell(j);
replaceCellWithLink(cell, "{{New/dual/topic upload}}", values[10] || "");
replaceCellWithLink(cell, "{{Attachment uploads}}", values[11] || "");
replaceCellWithLink(cell, "{{New course form for reactivation}}", values[27] || "");
replaceCellWithLink(cell, "{{Attachment uploads 2}}", values[20] || "");
replaceCellWithLink(cell, "{{Lib Ed proposals}}", values[33] || "");
replaceCellWithLink(cell, "{{New program proposal}}", values[29] || "");
replaceCellWithLink(cell, "{{Upload of program changes}}", values[30] || "");
replaceCellWithLink(cell, "{{Program discontinuation}}", values[32] || "");
}
}
});
}
/**
* Function to remove table rows where column 1 has content but column 2 is empty,
* and also remove rows where both columns are empty.
*/
function removeEmptySecondColumnRows(body) {
var tables = body.getTables();
if (tables.length === 0) return;
tables.forEach(table => {
var numRows = table.getNumRows();
// Iterate from bottom to top to avoid index shift issues when deleting
for (var i = numRows - 1; i >= 0; i--) {
var row = table.getRow(i);
var numCells = row.getNumCells();
if (numCells === 0) continue; // Skip empty rows
var firstCell = row.getCell(0);
var firstCellColSpan = firstCell.getColSpan();
var firstCellText = firstCell.getText().trim();
if (firstCellColSpan > 1) {
// The first cell spans multiple columns
if (firstCellText === "") {
table.removeRow(i); // Remove row if the merged cell is empty
}
// Otherwise, keep the row intact
} else if (numCells > 1) {
// The row has at least two separate cells
var secondCell = row.getCell(1);
var secondCellText = secondCell.getText().trim();
if (firstCellText === "" && secondCellText === "") {
table.removeRow(i); // Remove row if both cells are empty
} else if (firstCellText !== "" && secondCellText === "") {
table.removeRow(i); // Remove row if first cell has content but second is empty
}
// Otherwise, keep the row intact
} else {
// The row has only one cell that doesn't span multiple columns
if (firstCellText === "") {
table.removeRow(i); // Remove row if the single cell is empty
}
// Otherwise, keep the row intact
}
}
});
Logger.log("Relevant rows have been processed and removed as necessary.");
}
/**
* Function to replace a placeholder in a table cell with a hyperlink
*/
function replaceCellWithLink(cell, placeholder, url) {
var text = cell.getText();
if (text.includes(placeholder)) {
if (url && url !== "--") {
var fileName =
url.
includes(
"drive.google.com") ?
getFileNameFromUrl(
url) :
url;
cell.setText(fileName);
var link = cell.editAsText();
link.setLinkUrl(0, fileName.length - 1, url);
} else {
cell.setText(""); // Remove placeholder if no valid URL
}
}
}
/**
* Helper function to extract the file name from a Google Drive URL
*/
function getFileNameFromUrl(url) {
var fileId = extractFileIdFromUrl(url);
if (fileId) {
var file = DriveApp.getFileById(fileId);
return file.getName();
}
return "No file";
}
/**
* Helper function to extract file ID from a Google Drive URL
*/
function extractFileIdFromUrl(url) {
var match = url.match(/[-\w]{25,}/);
return match ? match[0] : null;
}