import { getColumnByName, getCellRangeByColumnName, getCellValueByColumnName, getColumnValuesByName, } from "./sheetUtils" export function newSkuHandler(e: GoogleAppsScript.Events.SheetsOnEdit) { var sheet = SpreadsheetApp.getActive().getActiveSheet() if (sheet.getName() !== "product_inventory") { console.log("skipping edit on sheet " + sheet.getName()) return } let row = e.range.getRowIndex() let idCell = getCellRangeByColumnName(sheet, "#", row) let idCellValue = idCell.getValue() console.log("idCellValue = '" + idCellValue + "'") if (idCellValue != "?" && idCellValue != "n") { console.log("new ID was not requested, returning") return } newSku(row) } export function newSku(row: number) { let sheet = SpreadsheetApp.getActive().getSheetByName("product_inventory") let skuPrefixCol = getColumnByName(sheet, "sku_prefix") console.log("skuPrefixCol: " + skuPrefixCol) let idCol = getColumnByName(sheet, "#") console.log("idCol: " + idCol) let idCell = getCellRangeByColumnName(sheet, "#", row) let safeToOverwrite: string[] = ["?", "n", ""] let idCellValue = idCell.getValue() let skuPrefixCellValue = getCellValueByColumnName(sheet, "sku_prefix", row) console.log("skuPrefixCellValue = '" + skuPrefixCellValue + "'") if (!safeToOverwrite.includes(idCellValue)) { console.log("ID '" + idCellValue + "' is not safe to overwrite, returning") return } var skuArray = getColumnValuesByName(sheet, "sku") var regExp = new RegExp(`^` + skuPrefixCellValue + `-0*(\\d+)$`) console.log("regExp: " + regExp.toString()) var maxId = 0 for (let i = 0; i < skuArray.length; i++) { console.log("checking row " + (i + 1)) if (null == skuArray[i] || String(skuArray[i]) == "") { console.log("SKU cell looks null") continue } console.log("SKU cell: '" + skuArray[i] + "'") var match = regExp.exec(String(skuArray[i])) if (null === match) { console.log("SKU cell did not match") continue } let numId = Number(match[1]) console.log("match: '" + match + "', numId: " + numId) maxId = Math.max(numId, maxId) console.log("numId: " + numId + ", maxId: " + maxId) } let newId = maxId + 1 console.log("newId: " + newId) idCell.setValue(newId) }