/** * X-ARENA for Google Sheets. * * This script lives in ONE master Google Sheet that you (the bot's owner) set * up once. Organisers press "Open the linked Google Sheet" on the panel, get * their own copy (the script comes with it), and then: * * X-ARENA → Connect… paste the code from the panel (once) * X-ARENA → Build the sheet tabs, formulas and colours for the tournament * X-ARENA → Send Final matches send every match whose Status is Final * X-ARENA → Send this match send the match on the open tab * * or tick "Send" on the Control tab — which also works in the phone app, * where menus do not. Draft matches are never sent, so nothing half-typed * reaches the scoreboard. Rebuilding never touches a match tab that already * has results typed in. * * The connect code holds the address to send to and a token for this one * tournament; it is kept in this sheet's document properties, not in a cell. */ var XA = { version: 2, prop: 'XARENA_CONNECTION', control: 'Control', meta: '_xarena', start: 'Start here', codePrefix: 'XA1-', }; function onOpen() { SpreadsheetApp.getUi() .createMenu('X-ARENA') .addItem('Connect…', 'xaConnect') .addItem('Build the sheet', 'xaBuild') .addSeparator() .addItem('Send Final matches', 'xaSendFinal') .addItem('Send this match', 'xaSendThis') .addSeparator() .addItem('Disconnect', 'xaDisconnect') .addToUi(); try { xaWelcome_(); } catch (e) { /* view-only, or nothing to do */ } } /** * A sheet not built yet (the master, or a fresh copy of it) says what to do, * instead of opening on an empty grid. Build replaces this tab with the * tournament's own Start here. */ function xaWelcome_() { var ss = SpreadsheetApp.getActive(); if (ss.getSheetByName(XA.meta) || ss.getSheetByName(XA.start)) return; var sheets = ss.getSheets(); var sheet = sheets[0]; if (sheets.length === 1 && sheet.getLastRow() === 0) { sheet.setName(XA.start); } else { sheet = ss.insertSheet(XA.start, 0); } var lines = [ 'X-ARENA results sheet', 'Not connected to a tournament yet. Three steps, once:', '1. Open this sheet in a browser: on a computer, or on a phone in Chrome (not the Google Sheets app, ' + 'which cannot show the X-ARENA menu).', '2. On the X-ARENA panel: Sheets → your tournament → Get a connect code. Copy it.', '3. Here: menu X-ARENA → Connect… and paste the code. Google asks once to allow the script: ' + 'Continue → Advanced → Go to … (unsafe) → Allow. It can only edit this sheet and send to X-ARENA.', 'The tournament\'s tabs then appear by themselves. Type each match, set its Status to Final, and send: ' + 'X-ARENA → Send Final matches, or tick Send on the Control tab (that works in the phone app too).', '', 'No X-ARENA menu? Reload the page; it appears a few seconds after the sheet opens.', 'Only a phone? Use the file instead: on the Sheets page, Download the sheet (.xlsx), open it in Google ' + 'Sheets, Share → Anyone with the link → Viewer, and connect its link on the Sheets page, then Go live. ' + 'Matches set to Final are recorded within seconds.', ]; sheet.getRange(1, 1, lines.length, 1).setValues(lines.map(function (l) { return [l]; })); sheet.setColumnWidth(1, 760); sheet.getRange(1, 1, lines.length, 1).setWrap(true).setVerticalAlignment('top'); sheet.getRange(1, 1).setFontSize(20).setFontWeight('bold'); sheet.getRange(2, 1).setFontWeight('bold'); ss.setActiveSheet(sheet); } // ── connection ──────────────────────────────────────────── function xaDecode_(code) { var text = String(code || '').trim(); if (text.indexOf(XA.codePrefix) !== 0) { throw new Error('That is not an X-ARENA code. Copy it again from the panel: Sheets → this tournament.'); } var b64 = text.slice(XA.codePrefix.length).replace(/-/g, '+').replace(/_/g, '/'); while (b64.length % 4) b64 += '='; var json = Utilities.newBlob(Utilities.base64Decode(b64)).getDataAsString(); var conn = JSON.parse(json); if (!conn || !/^https?:\/\//.test(conn.u || '') || !conn.t) throw new Error('That code is damaged. Copy it again.'); return conn; } function xaConnection_() { var raw = PropertiesService.getDocumentProperties().getProperty(XA.prop); if (!raw) throw new Error('This sheet is not connected yet: X-ARENA → Connect… and paste the code from the panel.'); return JSON.parse(raw); } function xaConnect() { var ui = SpreadsheetApp.getUi(); var answer = ui.prompt('Connect to X-ARENA', 'Paste the code from the panel (Sheets → your tournament → Linked Google Sheet).', ui.ButtonSet.OK_CANCEL); if (answer.getSelectedButton() !== ui.Button.OK) return; var conn = xaDecode_(answer.getResponseText()); PropertiesService.getDocumentProperties().setProperty(XA.prop, JSON.stringify(conn)); xaInstallTrigger_(); var spec = xaFetch_('get', '/layout', null).layout; xaRender_(spec); ui.alert('Connected', 'This sheet now sends to X-ARENA. Type results, set each match to Final, then ' + 'X-ARENA → Send Final matches (or tick Send on the Control tab).', ui.ButtonSet.OK); } function xaDisconnect() { PropertiesService.getDocumentProperties().deleteProperty(XA.prop); ScriptApp.getProjectTriggers().forEach(function (t) { if (t.getHandlerFunction() === 'xaOnEdit') ScriptApp.deleteTrigger(t); }); SpreadsheetApp.getActive().toast('Disconnected from X-ARENA.', 'X-ARENA', 5); } function xaInstallTrigger_() { var ss = SpreadsheetApp.getActive(); ScriptApp.getProjectTriggers().forEach(function (t) { if (t.getHandlerFunction() === 'xaOnEdit') ScriptApp.deleteTrigger(t); }); // Installable, so it may send over the network (a simple onEdit may not). ScriptApp.newTrigger('xaOnEdit').forSpreadsheet(ss).onEdit().create(); } function xaFetch_(method, path, payload) { var conn = xaConnection_(); var options = { method: method, muteHttpExceptions: true, headers: { 'X-Arena-Token': conn.t }, contentType: 'application/json', }; if (payload) options.payload = JSON.stringify(payload); var response = UrlFetchApp.fetch(conn.u + path, options); var body = {}; try { body = JSON.parse(response.getContentText() || '{}'); } catch (e) { body = {}; } if (response.getResponseCode() >= 300 || body.ok === false) { throw new Error(body.error || ('X-ARENA answered ' + response.getResponseCode() + '.')); } return body; } // ── building the sheet from X-ARENA's layout ────────────── function xaBuild() { var spec = xaFetch_('get', '/layout', null).layout; xaRender_(spec); SpreadsheetApp.getActive().toast('The sheet is up to date with X-ARENA.', 'X-ARENA', 5); } /** A match tab someone has typed into is never rebuilt (its results would go). */ function xaHasTyping_(sheet, tabSpec) { if (!sheet) return false; var built = {}; tabSpec.cells.forEach(function (c) { built[c[0] + ':' + c[1]] = c[2]; }); var range = sheet.getDataRange(); var values = range.getValues(); var formulas = range.getFormulas(); for (var r = 0; r < values.length; r++) { for (var c = 0; c < values[r].length; c++) { if (formulas[r][c]) continue; var v = values[r][c]; if (v === '' || v === null || v === false) continue; var was = built[(r + 1) + ':' + (c + 1)]; if (was === undefined || String(was) !== String(v)) return true; } } return false; } function xaIsEntryTab_(name) { return /^(Match|Race|Game|Attempt) \d+$/.test(name) || name === 'Matches' || name === 'Players'; } /** Looks Google refused during a build (the sheet still works without them). */ var XA_SKIPPED = []; function xaRender_(spec) { var ss = SpreadsheetApp.getActive(); var kept = []; XA_SKIPPED = []; spec.tabs.forEach(function (tabSpec, index) { var sheet = ss.getSheetByName(tabSpec.name); if (sheet && xaIsEntryTab_(tabSpec.name) && xaHasTyping_(sheet, tabSpec)) { kept.push(tabSpec.name); // leave the results alone } else { if (!sheet) sheet = ss.insertSheet(tabSpec.name); xaRenderTab_(ss, sheet, tabSpec, spec.styles); } if (!tabSpec.hidden) { // activating a hidden tab would show it ss.setActiveSheet(sheet); ss.moveActiveSheet(index + 1); } }); // The blank tab a new spreadsheet starts with. ['Sheet1', 'Feuille 1', 'Hoja 1'].forEach(function (name) { var blank = ss.getSheetByName(name); if (blank && ss.getSheets().length > 1 && blank.getLastRow() === 0) ss.deleteSheet(blank); }); var first = ss.getSheetByName(spec.tabs[0].name); if (first) ss.setActiveSheet(first); if (kept.length) { ss.toast('Kept as typed: ' + kept.join(', ') + '.', 'X-ARENA', 8); } if (XA_SKIPPED.length) { console.warn('X-ARENA build skipped: ' + XA_SKIPPED.join('; ')); ss.toast('Built. A few looks were skipped: ' + XA_SKIPPED.slice(0, 2).join('; '), 'X-ARENA', 10); } } function xaA1_(r, c) { var s = ''; while (c > 0) { var m = (c - 1) % 26; s = String.fromCharCode(65 + m) + s; c = Math.floor((c - 1) / 26); } return s + r; } function xaRenderTab_(ss, sheet, t, styles) { // Start clean. Frozen panes first: an old freeze would refuse the merges below. var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET); protections.forEach(function (p) { p.remove(); }); sheet.setFrozenRows(0); sheet.setFrozenColumns(0); sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).breakApart(); sheet.clear(); sheet.clearConditionalFormatRules(); sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).clearDataValidations(); sheet.showColumns(1, sheet.getMaxColumns()); var rows = Math.max(t.rows, 1), cols = Math.max(t.cols, 1); if (sheet.getMaxRows() < rows) sheet.insertRowsAfter(sheet.getMaxRows(), rows - sheet.getMaxRows()); if (sheet.getMaxColumns() < cols) sheet.insertColumnsAfter(sheet.getMaxColumns(), cols - sheet.getMaxColumns()); // Values and formulas, in one write. This is what matters; everything after is looks, // and a look Google refuses must not stop the rest of the sheet being built. var grid = []; for (var r = 0; r < rows; r++) { var line = []; for (var c = 0; c < cols; c++) line.push(''); grid.push(line); } var byStyle = {}; t.cells.forEach(function (cell) { var v = cell[2]; if (v !== null && v !== undefined) grid[cell[0] - 1][cell[1] - 1] = v; if (cell[3]) (byStyle[cell[3]] = byStyle[cell[3]] || []).push(xaA1_(cell[0], cell[1])); }); sheet.getRange(1, 1, rows, cols).setValues(grid); var safe = function (what, fn) { try { fn(); } catch (e) { XA_SKIPPED.push(t.name + ': ' + what + ' (' + e.message + ')'); } }; // Styles, a few calls per style rather than one per cell. safe('styles', function () { Object.keys(byStyle).forEach(function (name) { var s = styles[name] || {}; var list = sheet.getRangeList(byStyle[name]); if (s.bg) list.setBackground('#' + s.bg); list.setFontColor('#' + (s.fg || '0B0B0D')); list.setFontFamily(s.font || 'Arial'); list.setFontSize(s.size || 10); list.setFontWeight(s.bold ? 'bold' : 'normal'); list.setFontStyle(s.italic ? 'italic' : 'normal'); if (s.h) list.setHorizontalAlignment(s.h); list.setVerticalAlignment(s.v || 'middle'); list.setWrap(!!s.wrap); if (s.fmt) list.setNumberFormat(s.fmt); if (s.border) { list.setBorder(true, true, true, true, false, false, '#D9D4C7', SpreadsheetApp.BorderStyle.SOLID); if (s.border === 'block') list.setBorder(true, null, null, null, null, null, '#0B0B0D', SpreadsheetApp.BorderStyle.SOLID_MEDIUM); } }); (t.nowrap || []).forEach(function (rc) { sheet.getRange(rc[0], rc[1]).setWrap(false); }); }); safe('widths', function () { Object.keys(t.widths).forEach(function (c) { sheet.setColumnWidth(Number(c), Math.round(t.widths[c] * 7 + 5)); }); Object.keys(t.heights).forEach(function (r) { sheet.setRowHeight(Number(r), Math.round(t.heights[r] * 1.34)); }); }); safe('merged cells', function () { t.merges.forEach(function (m) { sheet.getRange(m[0], m[1], m[2] - m[0] + 1, m[3] - m[1] + 1).merge(); }); }); safe('frozen rows', function () { sheet.setFrozenRows(t.freeze ? t.freeze[0] - 1 : 0); }); safe('frozen columns', function () { sheet.setFrozenColumns(t.freeze ? t.freeze[1] - 1 : 0); }); (t.validations || []).forEach(function (v) { safe('a dropdown or number check on ' + v.range, function () { var b = SpreadsheetApp.newDataValidation().setAllowInvalid(false); if (v.kind === 'list') b = b.requireValueInList(v.values, true); else if (v.kind === 'range') b = b.requireValueInRange(ss.getRange(v.source), true); else if (v.kind === 'whole' || v.kind === 'decimal') b = b.requireNumberBetween(Number(v.lo || 0), Number(v.hi || 999999)); else if (v.kind === 'checkbox') b = b.requireCheckbox(); if (v.error) b = b.setHelpText(v.error); sheet.getRange(v.range).setDataValidation(b.build()); }); }); safe('colours that follow the results', function () { var rules = []; t.cond.forEach(function (c) { var b = SpreadsheetApp.newConditionalFormatRule().whenFormulaSatisfied('=' + c.formula); if (c.bg) b = b.setBackground('#' + c.bg); if (c.fg) b = b.setFontColor('#' + c.fg); if (c.bold) b = b.setBold(true); if (c.italic) b = b.setItalic(true); rules.push(b.setRanges([sheet.getRange(c.range)]).build()); }); t.bars.forEach(function (bar) { rules.push(SpreadsheetApp.newConditionalFormatRule() .setGradientMinpointWithValue('#FFFFFF', SpreadsheetApp.InterpolationType.NUMBER, '0') .setGradientMaxpoint('#' + bar.color) .setRanges([sheet.getRange(bar.range)]).build()); }); sheet.setConditionalFormatRules(rules); }); safe('hidden columns', function () { t.hide_cols.forEach(function (h) { sheet.hideColumns(h[0], h[1] - h[0] + 1); }); }); safe('tab colour', function () { if (t.color) sheet.setTabColor('#' + t.color); sheet.setHiddenGridlines(!t.gridlines); }); if (t.hidden) sheet.hideSheet(); else sheet.showSheet(); // A warning, not a lock: the organiser owns the sheet. safe('protection', function () { if (t.protect) sheet.protect().setDescription('Worked out by X-ARENA').setWarningOnly(true); }); } // ── sending ─────────────────────────────────────────────── function xaMeta_() { var sheet = SpreadsheetApp.getActive().getSheetByName(XA.meta); if (!sheet) throw new Error('This sheet has no X-ARENA layout yet: X-ARENA → Build the sheet.'); var col = sheet.getRange(1, 1, Math.max(sheet.getLastRow(), 1), 1).getDisplayValues(); var parts = []; for (var i = 1; i < col.length && col[i][0]; i++) parts.push(col[i][0]); return JSON.parse(parts.join('')); } function xaTabsToSend_(meta) { var ss = SpreadsheetApp.getActive(); var names = [XA.meta].concat(meta.match_tabs || []); if (meta.format === 'head_to_head') names.push('Matches', 'Players'); var tabs = {}; names.forEach(function (name) { var sheet = ss.getSheetByName(name); if (sheet) tabs[name] = sheet.getDataRange().getDisplayValues(); }); return tabs; } function xaSend_(only) { var lock = LockService.getDocumentLock(); if (!lock.tryLock(20000)) throw new Error('Another send is still running. Try again in a moment.'); try { var meta = xaMeta_(); var payload = { tabs: xaTabsToSend_(meta) }; if (only) payload.send = only; var result = xaFetch_('post', '', payload); xaWriteOutcomes_(result.matches || {}, only); return result; } finally { lock.releaseLock(); } } function xaSendFinal() { var result = xaSend_(null); SpreadsheetApp.getActive().toast(result.summary || 'Sent.', 'X-ARENA', 8); } function xaSendThis() { var name = SpreadsheetApp.getActive().getActiveSheet().getName(); var m = /(\d+)$/.exec(name); if (!m || !/^(Match|Race|Game|Attempt) \d+$/.test(name)) { throw new Error('Open a match tab (Match 3, Race 2 …) first, or use Send Final matches.'); } var result = xaSend_([Number(m[1])]); SpreadsheetApp.getActive().toast(result.summary || 'Sent.', 'X-ARENA', 8); } function xaWriteOutcomes_(outcomes, only) { var sheet = SpreadsheetApp.getActive().getSheetByName(XA.control); if (!sheet) return; var last = sheet.getLastRow(); if (last < 6) return; var rows = sheet.getRange(6, 1, last - 5, 5).getValues(); var now = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss'); var words = { sent: 'Sent', unchanged: 'Unchanged (already in X-ARENA)', draft: 'Draft — not sent' }; for (var i = 0; i < rows.length; i++) { var m = String(rows[i][0]); if (!(m in outcomes)) continue; if (only && only.indexOf(Number(m)) < 0) continue; var said = outcomes[m]; sheet.getRange(6 + i, 4).setValue(now); sheet.getRange(6 + i, 5).setValue(words[said] || said); } } /** The Control tab's tick boxes (an installable trigger: xaInstallTrigger_). */ function xaOnEdit(e) { if (!e || !e.range) return; var sheet = e.range.getSheet(); if (sheet.getName() !== XA.control || e.range.getColumn() !== 3 || e.range.getNumRows() !== 1) return; if (e.range.getValue() !== true) return; var row = e.range.getRow(); try { if (row === 5) { var all = xaSend_(null); sheet.getRange(5, 4).setValue(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss')); sheet.getRange(5, 5).setValue(all.summary || 'Sent.'); } else if (row >= 6) { var m = Number(sheet.getRange(row, 1).getValue()); if (m) xaSend_([m]); } } catch (err) { sheet.getRange(row, 5).setValue('Not sent: ' + err.message); } finally { e.range.setValue(false); } }