// The scenario planner on /tools. Everything typed stays in this browser tab: nothing is // sent, stored or remembered, and no email is asked for. import { ASSUMPTIONS, COSTS, LEVELS, LIMITATIONS, MAX_CHANNELS, OUTPUTS, combineScenarios, computeScenario, formatOutput, planToText, readNumber } from './scenario-planner.mjs'; const host = document.querySelector('[data-scenario-planner]'); if (host) { const el = (tag, props = {}, children = []) => { const node = document.createElement(tag); for (const [key, value] of Object.entries(props)) { if (key === 'text') node.textContent = value; else if (key === 'class') node.className = value; else if (value === true) node.setAttribute(key, ''); else if (value !== false && value !== undefined) node.setAttribute(key, value); } for (const child of [children].flat()) if (child) node.append(child); return node; }; const form = el('form', { class: 'form planner-form', novalidate: true }); const channelsBox = el('div', { class: 'planner-channels' }); const status = el('p', { class: 'form-status', role: 'status', 'aria-live': 'polite', tabindex: '-1' }); const results = el('div', { class: 'planner-results', hidden: true }); const addButton = el('button', { class: 'btn btn-outline', type: 'button', text: 'Add a channel' }); const calcButton = el('button', { class: 'btn btn-dark', type: 'submit', text: 'Work out the scenarios' }); const resetButton = el('button', { class: 'btn btn-outline', type: 'button', text: 'Clear everything' }); const saveButton = el('button', { class: 'btn btn-outline', type: 'button', text: 'Download as text', hidden: true }); let count = 0; let lastText = ''; function addChannel() { const n = ++count; const id = `planner-${n}`; const number = (fieldId, label, describedBy) => el('input', { id: fieldId, type: 'text', inputmode: 'decimal', autocomplete: 'off', 'aria-label': label, 'aria-describedby': describedBy }); const rows = ASSUMPTIONS.map(assumption => el('tr', {}, [ el('th', { scope: 'row' }, [el('span', { text: assumption.label }), assumption.hint ? el('span', { class: 'small planner-hint', id: `${id}-${assumption.id}-hint`, text: assumption.hint }) : null]), ...LEVELS.map(level => el('td', {}, number(`${id}-${assumption.id}-${level}`, `${assumption.label}, ${level} scenario`, assumption.hint ? `${id}-${assumption.id}-hint` : undefined))), ])); const fieldset = el('fieldset', { class: 'planner-channel', 'data-channel': String(n) }, [ el('legend', { text: `Channel ${n}` }), el('div', { class: 'field' }, [el('label', { for: `${id}-name`, text: 'Channel or scenario name' }), el('input', { id: `${id}-name`, type: 'text', maxlength: '60', placeholder: 'For example: YouTube integrations' })]), el('div', { class: 'table-scroll' }, el('table', { class: 'planner-table' }, [ el('caption', { class: 'sr-only', text: `Assumptions for channel ${n}, at three levels` }), el('thead', {}, el('tr', {}, [el('th', { scope: 'col', text: 'Your assumption' }), ...LEVELS.map(level => el('th', { scope: 'col', text: level[0].toUpperCase() + level.slice(1) }))])), el('tbody', {}, rows), ])), el('div', { class: 'field-pair planner-costs' }, COSTS.map(cost => el('div', { class: 'field' }, [el('label', { for: `${id}-cost-${cost.id}`, text: cost.label }), el('input', { id: `${id}-cost-${cost.id}`, type: 'text', inputmode: 'decimal', autocomplete: 'off' })]))), el('label', { class: 'check' }, [el('input', { type: 'checkbox', id: `${id}-from-media` }), el('span', { text: 'The revenue in this scenario comes from the paid media spend above (needed to show ROAS)' })]), n > 1 ? el('button', { class: 'link-button', type: 'button', 'data-remove': String(n), text: `Remove channel ${n}` }) : null, ]); channelsBox.append(fieldset); addButton.hidden = channelsBox.children.length >= MAX_CHANNELS; return fieldset; } const clearErrors = () => { for (const note of form.querySelectorAll('.field-error, .planner-warning')) note.remove(); for (const input of form.querySelectorAll('[aria-invalid]')) input.removeAttribute('aria-invalid'); }; const flag = (input, message, className) => { const note = el('p', { class: className, id: `${input.id}-note`, text: message }); if (className === 'field-error') input.setAttribute('aria-invalid', 'true'); input.after(note); }; function calculate() { clearErrors(); let firstInvalid = null; const read = (input, options) => { const result = readNumber(input.value, options); if (result.state === 'invalid') { flag(input, result.reason, 'field-error'); firstInvalid ||= input; } else if (result.warning) flag(input, result.warning, 'planner-warning'); return result.value; }; const channels = [...channelsBox.children].map(fieldset => { const id = `planner-${fieldset.dataset.channel}`; const costs = Object.fromEntries(COSTS.map(cost => [cost.id, read(form.querySelector(`#${id}-cost-${cost.id}`), { kind: 'money' })])); const revenueFromMedia = form.querySelector(`#${id}-from-media`).checked; const levels = Object.fromEntries(LEVELS.map(level => [level, computeScenario({ ...Object.fromEntries(ASSUMPTIONS.map(assumption => [assumption.id, read(form.querySelector(`#${id}-${assumption.id}-${level}`), assumption)])), costs, revenueFromMedia, })])); const notes = []; if (levels.base.costsLeftBlank.length && levels.base.totalCost !== null) notes.push(`Left out of total cost because they were blank: ${levels.base.costsLeftBlank.join(', ')}.`); const reason = levels.base.why.roas || levels.low.why.roas || levels.high.why.roas; if (reason) notes.push(`ROAS: ${reason}`); return { name: form.querySelector(`#${id}-name`).value.trim() || `Channel ${fieldset.dataset.channel}`, levels, notes }; }); if (firstInvalid) { results.hidden = true; saveButton.hidden = true; status.className = 'form-status bad'; status.textContent = 'Some entries are not usable numbers. They are marked above; nothing was worked out.'; firstInvalid.focus(); return; } const totals = Object.fromEntries(LEVELS.map(level => [level, combineScenarios(channels.map(channel => channel.levels[level]))])); const plan = { channels, totals }; const anything = channels.some(channel => LEVELS.some(level => OUTPUTS.some(output => channel.levels[level][output.id] !== null))); results.replaceChildren(); const table = (caption, byLevel) => el('div', { class: 'table-scroll' }, el('table', { class: 'compare planner-output' }, [ el('caption', { text: caption }), el('thead', {}, el('tr', {}, [el('th', { scope: 'col', text: 'Measure' }), ...LEVELS.map(level => el('th', { scope: 'col', text: level[0].toUpperCase() + level.slice(1) }))])), el('tbody', {}, OUTPUTS.map(output => el('tr', {}, [el('th', { scope: 'row', text: output.label }), ...LEVELS.map(level => el('td', { text: formatOutput(output, byLevel[level][output.id]) }))]))), ])); for (const channel of channels) { results.append(table(channel.name, channel.levels)); for (const note of channel.notes) results.append(el('p', { class: 'small', text: note })); } if (channels.length > 1) { results.append(table('All channels together', totals)); if (!totals.base.complete) results.append(el('p', { class: 'small', text: 'Some totals show n/a because at least one channel is missing that figure. A partial sum would be misleading.' })); } results.append(el('h3', { text: 'How to read this' }), el('ul', { class: 'plain-list' }, LIMITATIONS.map(item => el('li', { text: item })))); results.hidden = false; lastText = planToText(plan); saveButton.hidden = !anything; status.className = 'form-status ok'; status.textContent = anything ? 'Scenarios worked out below. They are planning figures, not a forecast.' : 'Nothing to work out yet: enter expected views and a click-through rate to begin.'; status.focus(); } form.addEventListener('submit', event => { event.preventDefault(); calculate(); }); addButton.addEventListener('click', () => { addChannel().querySelector('input').focus(); }); channelsBox.addEventListener('click', event => { const remove = event.target.closest('[data-remove]'); if (!remove) return; remove.closest('fieldset').remove(); addButton.hidden = channelsBox.children.length >= MAX_CHANNELS; addButton.focus(); }); resetButton.addEventListener('click', () => { channelsBox.replaceChildren(); count = 0; addChannel(); results.replaceChildren(); results.hidden = true; saveButton.hidden = true; lastText = ''; status.className = 'form-status'; status.textContent = 'Cleared.'; channelsBox.querySelector('input').focus(); }); saveButton.addEventListener('click', () => { const link = el('a', { href: URL.createObjectURL(new Blob([lastText], { type: 'text/plain' })), download: 'brandavenga-scenario-plan.txt' }); document.body.append(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(link.href), 1000); }); addChannel(); form.append(channelsBox, el('div', { class: 'actions' }, [calcButton, addButton, resetButton, saveButton]), status, results); host.replaceChildren(form); }