// EJI API for Google Sheets: My Data. Paste this whole file into Extensions > Apps Script // (replace what is there), save, then reload the sheet. Every formula starts with EJI_: type =EJI_ in a cell to see them, or use // EJI API > Insert formula… One sheet needs only this one script; to add an area, copy a new script that has it and paste over this one. // ===== EJI API core: one menu for every EJI family in this sheet (Finance, Accounting, Medical, ...) ===== /** @OnlyCurrentDoc */ // Google asks for this sheet only, not for all your Google Sheets // Every family part below registers itself with a function ejiFamily__(); nothing here depends on file order. var EJI_CATALOG_ = [{"family":"My Data","name":"EJI_MY_DATA","doc":"Rows of one of your datasets, with a header row, filling the cells below and to the right.","example":"=EJI_MY_DATA(\"clients\", \"city=Jaipur\")","params":[{"name":"dataset","desc":"the dataset's short name, e.g. \"clients\""},{"name":"filter","desc":"e.g. \"city=Jaipur\", \"amount__gte=1000\", \"q=sharma\"; several joined with &"},{"name":"fields","desc":"the columns to show, comma separated, e.g. \"client_name,city\""},{"name":"limit","desc":"how many rows, up to 1000 (default 500)"}]},{"family":"My Data","name":"EJI_MY_VALUE","doc":"One value from the row whose key column equals key. Works on a column of up to 50 keys.","example":"=EJI_MY_VALUE(\"clients\", \"Asha Sharma\", \"city\")","params":[{"name":"dataset","desc":"the dataset's short name"},{"name":"key","desc":"the value in the dataset's key column (set it on the Settings tab), or a range of them"},{"name":"field","desc":"the column to return, e.g. \"city\""}]},{"family":"My Data","name":"EJI_MY_COUNT","doc":"How many rows match a filter.","example":"=EJI_MY_COUNT(\"clients\", \"city=Jaipur\")","params":[{"name":"dataset","desc":"the dataset's short name"},{"name":"filter","desc":"e.g. \"city=Jaipur\"; several joined with &"}]},{"family":"My Data","name":"EJI_MY_DATASETS","doc":"Your datasets this key can read: short name, title, rows, last updated.","example":"=EJI_MY_DATASETS()","params":[]}]; function ejiFamilies_() { var out = []; if (typeof ejiFamily_fin_ === "function") out.push(ejiFamily_fin_()); if (typeof ejiFamily_acc_ === "function") out.push(ejiFamily_acc_()); if (typeof ejiFamily_med_ === "function") out.push(ejiFamily_med_()); if (typeof ejiFamily_my_ === "function") out.push(ejiFamily_my_()); return out; } function onOpen() { var ui = SpreadsheetApp.getUi(); var menu = ui.createMenu("EJI API") .addItem("Insert formula…", "ejiFormulaSidebar") .addItem("Add a formula guide tab", "ejiFormulaGuide") .addItem("Refresh values", "ejiRefresh") .addSeparator(); ejiFamilies_().forEach(function (f) { var sub = ui.createMenu(f.name); f.items.forEach(function (it) { sub.addItem(it[0], it[1]); }); menu.addSubMenu(sub); }); menu.addToUi(); } // Forget cached answers (every family) and enter the EJI formulas of the current sheet again, so their values are fetched // fresh. Nothing else is touched: other formulas and everything typed stay exactly as they are. function ejiRefresh() { ejiFamilies_().forEach(function (f) { if (f.bump) f.bump(); }); var sheet = SpreadsheetApp.getActiveSheet(); var formulas = sheet.getDataRange().getFormulas(); var mine = new RegExp("\\b(" + "EJI_[A-Z0-9_]+|TALLY_[A-Z0-9_]+|MED_[A-Z0-9_]+|IPOLISTGAIN|STOCKCLOSE|INDEXCLOSE|NAVRETURN|IPOSTATUS|FUNDNAME|IPOPRICE|FUNDNAV|IPODATE|IPOSUBS|INDEXPE|IPOLOT|IPOGMP|NAVON|FXINR|EJI" + ")\\s*\\(", "i"); var runs = []; formulas.forEach(function (row, i) { var j = 0; while (j < row.length) { if (!mine.test(row[j])) { j++; continue; } var start = j; while (j < row.length && mine.test(row[j])) j++; runs.push({ r: i + 1, c: start + 1, f: row.slice(start, j) }); } }); if (!runs.length) { SpreadsheetApp.getUi().alert("There are no EJI formulas on this sheet."); return; } // Clear, wait, enter again. Whatever happens in between, the formulas that were cleared are put back (finally). var cleared = [], failed = []; try { runs.forEach(function (x) { sheet.getRange(x.r, x.c, 1, x.f.length).clearContent(); cleared.push(x); }); SpreadsheetApp.flush(); } finally { cleared.forEach(function (x) { try { sheet.getRange(x.r, x.c, 1, x.f.length).setFormulas([x.f]); } catch (e) { failed.push(x.r + ":" + x.c); } }); } if (failed.length) throw new Error("Could not enter the formulas again at row:column " + failed.join(", ") + ". Use Edit > Undo to bring them back."); } // ---- fields: one value out of an API answer ---- // A dotted field of the answer: latestNav, returns.1y, 0.nav (first item), -1.nav (last), *.nav (every item: a column). function ejiField_(data, field) { var parts = (field == null || String(field).trim() === "") ? [] : String(field).trim().split("."); function walk(v, i) { if (i >= parts.length) return v; var k = parts[i]; if (k === "*") { if (!Array.isArray(v)) throw new Error("* needs a list"); return v.map(function (x) { return walk(x, i + 1); }); } if (Array.isArray(v)) { if (!/^-?\d+$/.test(k)) throw new Error("This is a list: use 0 for the first item, -1 for the last, or * for all"); var x = v[Number(k) < 0 ? v.length + Number(k) : Number(k)]; if (x === undefined) throw new Error("The list has " + v.length + " items, no item " + k); return walk(x, i + 1); } if (v === null || typeof v !== "object" || !Object.prototype.hasOwnProperty.call(v, k)) { var here = (v !== null && typeof v === "object") ? Object.keys(v).slice(0, 12).join(", ") : ""; throw new Error("No field " + parts.slice(0, i + 1).join(".") + (here ? ". Fields here: " + here : "")); } return walk(v[k], i + 1); } function cell(x) { if (x === null || x === undefined) return ""; if (typeof x === "object") throw new Error("That is a group of fields; pick one inside it: " + Object.keys(x).slice(0, 6).join(", ")); return x; } var v = walk(data, 0); if (Array.isArray(v)) return v.length ? v.map(function (x) { return [cell(x)]; }) : ""; return cell(v); } // Every single-value field of an answer as [field, sample]: objects opened, a list as "0.x" and "*.x". function ejiListFields_(data) { var out = []; function visit(v, at, depth) { if (out.length >= 300) return; if (v === null || typeof v !== "object") { if (at) out.push([at, v === null || v === undefined ? "" : v]); return; } if (depth > 5) return; if (Array.isArray(v)) { if (!v.length) return; var pre = at ? at + "." : ""; if (v[0] !== null && typeof v[0] === "object" && !Array.isArray(v[0])) { Object.keys(v[0]).forEach(function (k) { var x = v[0][k]; if (x === null || typeof x !== "object") out.push([pre + "*." + k, x === null ? "" : x]); }); } else if (v[0] === null || typeof v[0] !== "object") out.push([pre + "*", v[0]]); visit(v[0], pre + "0", depth + 1); return; } Object.keys(v).forEach(function (k) { visit(v[k], at ? at + "." + k : k, depth + 1); }); } visit(data, "", 0); return out; } // What a cell shows when the field is left empty: the fields to choose from. function ejiPickHint_(data) { var names = ejiListFields_(data).map(function (f) { return f[0]; }).filter(function (n) { return n.indexOf("*") < 0; }); return names.length ? "Pick a field: " + names.slice(0, 40).join(", ") + (names.length > 40 ? ", …" : "") : "This answer has no fields"; } // ---- Insert formula… (a sidebar) and the formula guide tab ---- var EJI_SIDEBAR_ = "\n\n\n\n
\n
\n \n
\n
\n\n

\n\n\n"; function ejiFormulaSidebar() { var fields = []; ejiFamilies_().forEach(function (f) { (f.fields || []).forEach(function (s) { fields.push({ fn: s.fn, label: f.name + ": " + s.label, arg: s.arg, example: s.example }); }); }); var data = "var CAT = " + JSON.stringify(EJI_CATALOG_) + ", FIELDS = " + JSON.stringify(fields) + ";"; var html = HtmlService.createHtmlOutput(EJI_SIDEBAR_.replace("/*DATA*/", data.replace(/ 0) { var m = (n - 1) % 26; s = String.fromCharCode(65 + m) + s; n = Math.floor((n - 1) / 26); } return s; } // Called by the sidebar: a table at the selected cell. A header row, then one row per value, each formula reading its row's value. function ejiInsertTable(fn, keysText, fields) { var spec = ejiFieldSpec_(fn); var keys = String(keysText == null ? "" : keysText).split(/[,;\n]+/).map(function (k) { return k.trim(); }).filter(Boolean); if (!keys.length) keys = [spec.example]; fields = (fields || []).map(String).filter(function (f) { return /^[A-Za-z0-9_.\-]+$/.test(f); }); if (!fields.length) throw new Error("Tick at least one field"); var cell = SpreadsheetApp.getActiveRange().getCell(1, 1), sh = cell.getSheet(), r0 = cell.getRow(), c0 = cell.getColumn(); var col = ejiColName_(c0); var rows = [[spec.arg].concat(fields)]; keys.forEach(function (k, i) { rows.push([k].concat(fields.map(function (f) { return "=" + fn + "(" + col + (r0 + 1 + i) + ", \"" + f + "\")"; }))); }); var range = sh.getRange(r0, c0, rows.length, rows[0].length); range.setValues(rows); sh.getRange(r0, c0, 1, rows[0].length).setFontWeight("bold"); return range.getA1Notation(); } // A tab named "EJI formulas" listing every formula of this script, what it gives and an example to copy. function ejiFormulaGuide() { var ss = SpreadsheetApp.getActive(); var sh = ss.getSheetByName("EJI formulas") || ss.insertSheet("EJI formulas"); sh.clear(); var rows = [["Area", "Formula", "What it gives", "Example (copy into a cell)"]].concat(EJI_CATALOG_.map(function (c) { return [c.family, c.name + "(" + c.params.map(function (p) { return p.name; }).join(", ") + ")", c.doc, c.example ? "'" + c.example : ""]; })); sh.getRange(1, 1, rows.length, 4).setValues(rows); sh.getRange(1, 1, 1, 4).setFontWeight("bold"); sh.setFrozenRows(1); sh.autoResizeColumns(1, 2); sh.setColumnWidth(3, 460); sh.setColumnWidth(4, 320); ss.setActiveSheet(sh); } // ===== end of the core ===== // EJI API My Data for Google Sheets. This is the My Data part of an EJI API script. // Menu "EJI API" > My Data > Set API key stores your My Data key (my_...) in this script's properties, never in a cell. // Your datasets are your own uploads at my.ejiapi.com/app; masked columns come back masked, as in every answer. // // A filter is written like the API's query: "city=Jaipur", "amount__gte=1000", several joined with &: // "city=Jaipur&amount__gte=1000". Search every text column with "q=sharma". var EJI_MY_BASE_ = "https://my.ejiapi.com/api/my/v1"; var EJI_MY_CACHE_SECONDS_ = 600; // 10 minutes; EJI API > Refresh values fetches fresh rows var EJI_MY_MAX_CELLS_ = 50; // keys looked up one by one, so a range is capped // ---------- plumbing ---------- function ejiMy_(path) { var props = PropertiesService.getScriptProperties(); var cacheKey = "y" + (props.getProperty("EJI_MY_CACHE_V") || "0") + ":" + path; if (cacheKey.length > 240) cacheKey = cacheKey.slice(0, 200) + Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, cacheKey)); var cache = CacheService.getScriptCache(); var hit = cache.get(cacheKey); if (hit) return JSON.parse(hit); var key = props.getProperty("EJI_MY_KEY"); if (!key) throw new Error("Set your key first: menu EJI API > My Data > Set API key"); var res; try { res = UrlFetchApp.fetch(EJI_MY_BASE_ + path, { method: "get", headers: { "X-API-Key": key, "X-Client": "sheets" }, muteHttpExceptions: true }); } catch (e) { throw new Error("Could not reach EJI (" + e.message + "). Run EJI API > My Data > Check setup once to give the script permission."); } var text = res.getContentText(), code = res.getResponseCode(); if (code !== 200) { var detail = text; try { detail = JSON.parse(text).detail || text; } catch (e) {} throw new Error(code === 401 ? "The My Data key was not accepted. EJI API > My Data > Set API key." : String(detail).slice(0, 160)); } if (text.length < 90000) cache.put(cacheKey, text, EJI_MY_CACHE_SECONDS_); // a cached value may not exceed 100 KB return JSON.parse(text); } function ejiMyName_(dataset) { var s = dataset === undefined || dataset === null ? "" : String(dataset).trim().toLowerCase(); if (!/^[a-z][a-z0-9_-]{0,39}$/.test(s)) throw new Error("Give a dataset's short name, e.g. \"clients\" (see =EJI_MY_DATASETS())"); return s; } // "city=Jaipur&amount__gte=1000" as a query string, every value encoded. function ejiMyFilter_(filter) { var s = filter === undefined || filter === null ? "" : String(filter).trim(); if (!s) return []; return s.split("&").filter(function (p) { return p.trim(); }).map(function (p) { var i = p.indexOf("="); if (i < 1) throw new Error("A filter looks like column=value, e.g. \"city=Jaipur\" or \"amount__gte=1000\""); var k = p.slice(0, i).trim(), v = p.slice(i + 1).trim(); if (!/^[a-z][a-z0-9_]*(__[a-z]+)?$|^q$/.test(k)) throw new Error("'" + k + "' is not a column name (use the API names on the Columns tab)"); return encodeURIComponent(k) + "=" + encodeURIComponent(v); }); } function ejiMyCell_(v) { if (v === null || v === undefined) return ""; if (typeof v === "boolean") return v; return v; } // ---------- datasets ---------- /** Rows of one of your datasets, with a header row, filling the cells below and to the right. =EJI_MY_DATA("clients", "city=Jaipur") * @param {string} dataset the dataset's short name, e.g. "clients" * @param {string} [filter] e.g. "city=Jaipur", "amount__gte=1000", "q=sharma"; several joined with & * @param {string} [fields] the columns to show, comma separated, e.g. "client_name,city" * @param {number} [limit] how many rows, up to 1000 (default 500) * @customfunction */ function EJI_MY_DATA(dataset, filter, fields, limit) { var name = ejiMyName_(dataset); var q = ejiMyFilter_(filter); if (fields) q.push("fields=" + encodeURIComponent(String(fields).replace(/\s+/g, ""))); var n = limit === undefined || limit === null || limit === "" ? 500 : Math.floor(Number(limit)); if (!(n >= 1)) throw new Error("limit must be a number from 1 to 1000"); q.push("limit=" + Math.min(n, 1000)); var r = ejiMy_("/datasets/" + name + "/rows?" + q.join("&")); var cols = r.meta.fields; if (!r.data.length) return [cols, cols.map(function (c, i) { return i === 0 ? "No rows match" : ""; })]; return [cols].concat(r.data.map(function (row) { return cols.map(function (c) { return ejiMyCell_(row[c]); }); })); } /** One value from the row whose key column equals key. Works on a column of up to 50 keys. =EJI_MY_VALUE("clients", "Asha Sharma", "city") * @param {string} dataset the dataset's short name * @param {string|Array} key the value in the dataset's key column (set it on the Settings tab), or a range of them * @param {string} field the column to return, e.g. "city" * @customfunction */ function EJI_MY_VALUE(dataset, key, field) { var name = ejiMyName_(dataset); var f = String(field == null ? "" : field).trim(); if (!f) throw new Error("Say which column to return, e.g. \"city\""); var one = function (k) { var r = ejiMy_("/datasets/" + name + "/rows/" + encodeURIComponent(String(k).trim())); if (!(f in r.data)) throw new Error("There is no column '" + f + "'"); return ejiMyCell_(r.data[f]); }; if (!Array.isArray(key)) return one(key); var cells = []; key.forEach(function (row) { (Array.isArray(row) ? row : [row]).forEach(function (x) { cells.push(x); }); }); if (cells.filter(function (x) { return x !== "" && x !== null; }).length > EJI_MY_MAX_CELLS_) throw new Error("Up to " + EJI_MY_MAX_CELLS_ + " keys per formula; split the range"); return cells.map(function (x) { if (x === "" || x === null) return [""]; try { return [one(x)]; } catch (e) { return ["#N/A " + e.message.slice(0, 60)]; } }); } /** How many rows match a filter. =EJI_MY_COUNT("clients", "city=Jaipur") * @param {string} dataset the dataset's short name * @param {string} [filter] e.g. "city=Jaipur"; several joined with & * @customfunction */ function EJI_MY_COUNT(dataset, filter) { var q = ejiMyFilter_(filter); q.push("limit=1"); q.push("fields=" + "_row"); return ejiMy_("/datasets/" + ejiMyName_(dataset) + "/rows?" + q.join("&")).meta.total; } /** Your datasets this key can read: short name, title, rows, last updated. =EJI_MY_DATASETS() * @customfunction */ function EJI_MY_DATASETS() { var d = ejiMy_("/datasets").data; return [["Name", "Title", "Rows", "Updated"]].concat(d.map(function (x) { return [x.name, x.title, x.rows, new Date(x.updated * 1000)]; })); } // ---------- menu ---------- function ejiMySetKey() { var ui = SpreadsheetApp.getUi(); var r = ui.prompt("EJI My Data", "Paste your My Data key (it starts my_). Make one at my.ejiapi.com/app", ui.ButtonSet.OK_CANCEL); if (r.getSelectedButton() !== ui.Button.OK) return; var key = r.getResponseText().trim(); if (!/^my_[A-Za-z0-9_-]{10,}$/.test(key)) { ui.alert("That does not look like a My Data key (my_...)."); return; } PropertiesService.getScriptProperties().setProperty("EJI_MY_KEY", key); ejiMyBump_(); ui.alert("Key saved. Try =EJI_MY_DATASETS() in any cell."); } function ejiMyCheck() { var ui = SpreadsheetApp.getUi(); try { var d = ejiMy_("/datasets").data; ui.alert("All set. This key can read " + d.length + " dataset" + (d.length === 1 ? "" : "s") + (d.length ? ": " + d.map(function (x) { return x.name; }).join(", ") : "") + "."); } catch (e) { ui.alert("Not working yet: " + e.message); } } // ---------- family registration (the core's EJI API menu shows these under My Data) ---------- function ejiFamily_my_() { return { id: "my", name: "My Data", bump: function () { ejiMyBump_(); }, items: [["Set API key", "ejiMySetKey"], ["Check setup", "ejiMyCheck"]], fields: [] }; } function ejiMyBump_() { var props = PropertiesService.getScriptProperties(); props.setProperty("EJI_MY_CACHE_V", String(Number(props.getProperty("EJI_MY_CACHE_V") || "0") + 1)); }