create-heresay 0.2.41 → 0.2.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.2.41",
3
+ "version": "0.2.43",
4
4
  "description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/release/VERSION CHANGED
@@ -1 +1 @@
1
- 0.2.41
1
+ 0.2.43
@@ -18,7 +18,9 @@ export function notificationView(settings) {
18
18
  cliq: { enabled: settings.cliq.enabled, configured: !!settings.cliq.token, endpoint: settings.cliq.endpoint },
19
19
  };
20
20
  }
21
- const telegramChanged = (a, b) => (a?.token ?? null) !== b.token || (a?.enabled ?? false) !== b.enabled;
21
+ // Also when it's on but the bot has no webhook yet (saved before buttons existed, or a failed attempt),
22
+ // so saving again fixes it without turning Telegram off and on.
23
+ const telegramChanged = (a, b) => (a?.token ?? null) !== b.token || (a?.enabled ?? false) !== b.enabled || (b.enabled && !!b.token && !b.webhook_url);
22
24
  class SettingsError extends Error {
23
25
  }
24
26
  const TELEGRAM_TOKEN = /^\d+:[A-Za-z0-9_-]{20,}$/;
@@ -205,7 +207,7 @@ export async function notificationSettings(p, req, deps, body) {
205
207
  if (!deps.sendNotification)
206
208
  return json(503, { error: 'Notification delivery is unavailable.' });
207
209
  try {
208
- await deps.sendNotification(provider, target, 'Heresay notifications are connected. You will receive the events selected in Notifications.');
210
+ await deps.sendNotification(provider, target, '✅ Heresay is connected. You will get the alerts you chose in Notifications.');
209
211
  return json(200, { ok: true });
210
212
  }
211
213
  catch {
@@ -214,6 +216,11 @@ export async function notificationSettings(p, req, deps, body) {
214
216
  }
215
217
  return json(404, { error: 'not found' });
216
218
  }
219
+ const HEADLINE = {
220
+ new_report: ['🔔', 'New report'], accepted: ['✅', 'Accepted'], fixed: ['🛠️', 'Fixed'], handoff: ['🔁', 'Handed off'],
221
+ };
222
+ const TYPE = { broken: ['🐞', 'Broken'], confusing: ['🤔', 'Confusing'], improvement: ['✨', 'Improvement'], idea: ['💡', 'Idea'] };
223
+ const esc = (t) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
217
224
  const actionsReady = (tg) => !!(tg.webhook_secret && tg.webhook_url);
218
225
  /** Metadata only: open reports and reporter details must never flow into an integration. */
219
226
  export async function notify(event, project, reportId, deps) {
@@ -225,16 +232,24 @@ export async function notify(event, project, reportId, deps) {
225
232
  new_report: 'A new report needs your review', accepted: 'A report was accepted for a coding agent',
226
233
  fixed: 'A report was marked fixed', handoff: 'A coding agent handed off a report',
227
234
  };
235
+ const [emoji, head] = HEADLINE[event];
236
+ // The type is one of four fixed words, never the reporter's text.
237
+ const found = await deps.store.getReport(project.id, reportId).catch(() => null);
238
+ const type = (found && TYPE[found.type]) || null;
228
239
  const origin = deps.selfOrigins?.[0];
229
- const text = `Heresay: ${labels[event]}.\nApp: ${project.name}\nReport: ${reportId}`
230
- + (origin ? `\n${origin}/app/#/apps/${encodeURIComponent(project.id)}` : '');
240
+ const link = origin ? `${origin}/app/#/apps/${encodeURIComponent(project.id)}` : null;
241
+ const meta = [type ? `${type[0]} ${type[1]}` : null, reportId];
242
+ const text = [`${emoji} ${head} · ${project.name}`, `${labels[event]}.`, meta.filter(Boolean).join(' · ')].join('\n') + (link ? `\n${link}` : '');
243
+ // Telegram gets bold and a link; the app name is the team's own, escaped, and nothing from a reporter is in it.
244
+ const html = `${emoji} <b>${esc(head)}</b> · ${esc(project.name)}\n${esc(labels[event])}.\n${type ? `${type[0]} ${type[1]} · ` : ''}<code>${esc(reportId)}</code>`
245
+ + (link ? `\n<a href="${esc(link)}">Open in Heresay →</a>` : '');
231
246
  await Promise.all(['telegram', 'cliq'].map(async (provider) => {
232
247
  if (!settings[provider].enabled)
233
248
  return;
234
249
  try {
235
250
  const markup = provider === 'telegram' && event === 'new_report' && actionsReady(settings.telegram)
236
251
  ? reportKeyboard(project.id, reportId) : null;
237
- await deps.sendNotification(provider, settings[provider], text, markup ? { telegram_markup: markup } : undefined);
252
+ await deps.sendNotification(provider, settings[provider], provider === 'telegram' ? html : text, provider === 'telegram' ? { telegram_html: true, ...(markup ? { telegram_markup: markup } : {}) } : undefined);
238
253
  deps.log('api.notification_sent', { provider, notification_event: event, project_id: project.id, report_id: reportId });
239
254
  }
240
255
  catch {
@@ -256,7 +271,7 @@ export function notificationSender(http = fetch) {
256
271
  throw new Error('Notification token missing.');
257
272
  if (provider === 'telegram' && 'chat_id' in destination) {
258
273
  url = `https://api.telegram.org/bot${destination.token}/sendMessage`;
259
- body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true }, ...(extra?.telegram_markup ? { reply_markup: extra.telegram_markup } : {}) };
274
+ body = { chat_id: destination.chat_id, text, ...(extra?.telegram_html ? { parse_mode: 'HTML' } : {}), link_preview_options: { is_disabled: true }, ...(extra?.telegram_markup ? { reply_markup: extra.telegram_markup } : {}) };
260
275
  }
261
276
  else if (provider === 'cliq' && 'endpoint' in destination && validCliqEndpoint(destination.endpoint)) {
262
277
  const u = new URL(destination.endpoint);
@@ -36,9 +36,9 @@ export function reportKeyboard(project_id, report_id) {
36
36
  if (Buffer.byteLength(data('a')) > 64)
37
37
  return null;
38
38
  return { inline_keyboard: [[
39
- { text: 'Accept', callback_data: data('a') },
40
- { text: 'Decline', callback_data: data('d') },
41
- { text: 'Show full text', callback_data: data('t') },
39
+ { text: '✅ Accept', callback_data: data('a') },
40
+ { text: '✖️ Decline', callback_data: data('d') },
41
+ { text: '📄 Full text', callback_data: data('t') },
42
42
  ]] };
43
43
  }
44
44
  // ---- keeping Telegram's webhook in step with the saved bot ----------------------------------
@@ -253,7 +253,7 @@ async function handleUpdate(u, members, tg, deps, triage) {
253
253
  const res = await triage(project, report.id, 'accept', email, fakeReq(), deps);
254
254
  if (res.status === 200) {
255
255
  await answer('Accepted');
256
- await finish(api, token, cb.message, `Accepted by ${email}`);
256
+ await finish(api, token, cb.message, `✅ Accepted by ${email}`);
257
257
  return;
258
258
  }
259
259
  await alreadyOrFail(res, project, report.id, answer, cb.message);
@@ -346,7 +346,7 @@ async function handleUpdate(u, members, tg, deps, triage) {
346
346
  const original = { message_id: Number(pending.data.message_id), chat: msg.chat, text: String(pending.data.text ?? '') };
347
347
  if (res.status === 200) {
348
348
  await deps.store.deleteAuth('decline', key);
349
- await finish(api, token, original, `Declined by ${email}: ${text}`);
349
+ await finish(api, token, original, `✖️ Declined by ${email}: ${text}`);
350
350
  await reply('Declined. The reporter will see your reason.');
351
351
  return;
352
352
  }
@@ -376,7 +376,9 @@ const fakeReq = (body = {}) => ({ method: 'POST', path: '', query: {}, headers:
376
376
  async function finish(api, token, message, line) {
377
377
  await api(token, 'editMessageText', {
378
378
  chat_id: message.chat.id, message_id: message.message_id,
379
- text: capText(`${(message.text ?? '').replace(/\n\n(Accepted|Declined) by [\s\S]*$/, '')}\n\n${line}`.trim()),
379
+ text: capText(`${(message.text ?? '').replace(/\n\n(✅ Accepted|✖️ Declined|Accepted|Declined) by [\s\S]*$/, '')}\n\n${line}`.trim()),
380
+ // The alert's bold and link, kept: the outcome is added after them, so their positions still hold.
381
+ ...(message.entities?.length ? { entities: message.entities } : {}),
380
382
  link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [] },
381
383
  });
382
384
  }
@@ -1,3 +1,3 @@
1
1
  /** The Heresay release. Bumped by the release script; the CLI and /v1/health report it. */
2
- export const VERSION = '0.2.41';
2
+ export const VERSION = '0.2.43';
3
3
  //# sourceMappingURL=version.js.map
@@ -506,3 +506,31 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
506
506
 
507
507
  .status.s-withdrawn { background:rgba(127,127,127,.14); color:var(--mute); }
508
508
  .report .reason.withdrawn { color:var(--mute); }
509
+
510
+ /* Notifications: small modules, each one a place alerts go or a thing to choose. */
511
+ .notify { max-width:720px; }
512
+ .module { padding:20px 24px; }
513
+ .module-head { display:flex; align-items:center; gap:12px; margin-bottom:6px; }
514
+ .module-head h2 { margin:0; font-size:18px; }
515
+ .module-head .spacer, .module-row .grow { flex:1; min-width:0; }
516
+ .pill-state { font-size:12px; font-weight:600; padding:3px 10px; border-radius:999px; background:var(--soft); color:var(--mute); }
517
+ .pill-state.on { background:var(--mist); color:var(--deep); }
518
+ .saved-tick { font-size:13px; color:var(--deep); }
519
+ .module-row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; padding:12px 0; border-top:1px solid var(--line); }
520
+ .module-row:first-of-type { border-top:0; }
521
+ .module-row .grow { color:var(--mute); }
522
+ .module-row .grow.ok-msg { color:var(--deep); }
523
+ .module-row .grow-line { flex-basis:100%; margin:0; }
524
+ .link-code { flex-basis:100%; }
525
+ .module-panel { border-top:1px solid var(--line); padding-top:4px; }
526
+ .module-panel[hidden], .module [hidden] { display:none; }
527
+ .module-more { margin-top:18px; }
528
+ .switch-row { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:13px 0; border-top:1px solid var(--line); cursor:pointer; }
529
+ .switch-row .hint { display:inline; margin:0; }
530
+ .switch { appearance:none; -webkit-appearance:none; width:38px; height:22px; border-radius:999px; background:var(--line); position:relative; cursor:pointer; flex:none; border:0; margin:0; padding:0; transition:background .15s; }
531
+ .switch::after { content:""; position:absolute; top:3px; left:3px; width:16px; height:16px; border-radius:50%; background:#fff; box-shadow:0 1px 2px rgb(0 0 0 / .25); transition:transform .15s; }
532
+ .switch:checked { background:var(--acc); }
533
+ .switch:checked::after { transform:translateX(16px); }
534
+ .switch:focus-visible { outline:2px solid var(--acc); outline-offset:2px; }
535
+ .switch:disabled { opacity:.5; cursor:default; }
536
+ @media (prefers-reduced-motion: reduce) { .switch, .switch::after { transition:none; } }
@@ -2115,298 +2115,339 @@
2115
2115
 
2116
2116
  // ---- notifications ---------------------------------------------------------------------
2117
2117
 
2118
+ /** The page is a stack of small modules: where alerts go (one per place), what to send, and your own Telegram link. */
2118
2119
  function notificationsView(view) {
2119
2120
  view.appendChild(el('div', { class: 'head' }, [el('h1', { text: 'Notifications' })]));
2120
- view.appendChild(el('p', { class: 'mute', text: 'Know when a report needs a hearing, or when work moves forward. These settings apply to every app in this Heresay.' }));
2121
+ var content = el('div', { class: 'notify' }, [loading()]);
2122
+ view.appendChild(content);
2121
2123
  if (me.role !== 'owner') {
2122
- view.appendChild(el('section', { class: 'card' }, [el('p', { text: 'An owner can connect Telegram or Zoho Cliq and choose which events your team receives.' }), el('a', { href: '#/team', text: 'See team owners' })]));
2123
- telegramActions(view);
2124
+ content.textContent = '';
2125
+ content.appendChild(el('p', { class: 'mute', text: 'Owners choose where alerts go.' }));
2126
+ var row = telegramLink({});
2127
+ content.appendChild(el('section', { class: 'card module' }, [el('div', { class: 'module-head' }, [el('h2', { text: 'Telegram' })]), row]));
2124
2128
  return;
2125
2129
  }
2126
- var content = el('div', {}, [loading()]);
2127
- view.appendChild(content);
2128
2130
  api('GET', '/notifications').then(function (b) {
2131
+ content.textContent = '';
2129
2132
  var settings = b.notifications;
2130
- var choices = [
2131
- ['new_report', 'New reports', 'A new report is waiting for a person to review it.'],
2132
- ['accepted', 'Accepted reports', 'A person approved a report for a coding agent.'],
2133
- ['fixed', 'Reports marked fixed', 'A teammate or coding agent marked a report fixed.'],
2134
- ['handoff', 'Agent handoffs', 'An agent handed accepted work to another repo.'],
2135
- ];
2136
- var eventInputs = {};
2137
- var eventsMsg = el('p', { role: 'status' });
2138
- var eventSave = el('button', { class: 'btn primary', type: 'submit', text: 'Save events' });
2139
- var eventsForm = el('form', { class: 'form notification-form' }, choices.map(function (choice) {
2140
- var input = eventInputs[choice[0]] = el('input', { type: 'checkbox', name: choice[0], checked: settings.events[choice[0]] });
2141
- return el('label', { class: 'notification-choice' }, [input, el('span', {}, [el('b', { text: choice[1] }), el('span', { class: 'hint', text: choice[2] })])]);
2142
- }).concat([el('div', { class: 'row' }, [eventSave]), eventsMsg]));
2143
- eventsForm.onsubmit = function (e) {
2144
- e.preventDefault();
2145
- var events = {};
2146
- Object.keys(eventInputs).forEach(function (key) { events[key] = eventInputs[key].checked; eventInputs[key].disabled = true; });
2147
- eventSave.disabled = true;
2148
- eventsMsg.className = 'hint'; eventsMsg.textContent = 'Saving…';
2149
- api('PATCH', '/notifications', { events: events }).then(function () {
2150
- eventsMsg.className = 'ok-msg'; eventsMsg.textContent = 'Notification events saved.';
2151
- }).catch(function (x) { eventsMsg.className = 'err'; eventsMsg.textContent = x.message; }).finally(function () {
2152
- eventSave.disabled = false;
2153
- Object.keys(eventInputs).forEach(function (key) { eventInputs[key].disabled = false; });
2154
- });
2155
- };
2156
- content.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'When to notify' }), eventsForm]));
2157
- content.appendChild(el('p', { class: 'hint', text: 'Alerts include the app name, event, report ID, and a link to the dashboard. Reporter text and contact details stay in Heresay.' }));
2158
- destination('telegram', 'Telegram', settings.telegram);
2159
- telegramActions(content);
2160
- destination('cliq', 'Zoho Cliq', settings.cliq);
2161
-
2162
- function destination(provider, title, saved) {
2163
- var telegram = provider === 'telegram', dirty = false;
2164
- var enabled = el('input', { type: 'checkbox', name: provider + '_enabled', checked: saved.enabled });
2165
- var token = el('input', { type: 'password', name: provider + '_token', maxlength: 512, autocomplete: 'new-password', spellcheck: 'false' });
2166
- var address = el('input', { type: 'text', name: telegram ? 'chat_id' : 'endpoint', value: telegram ? saved.chat_id : saved.endpoint, maxlength: telegram ? 100 : 300, autocomplete: 'off', spellcheck: 'false', placeholder: telegram ? '-1001234567890 or @yourchannel' : 'https://cliq.zoho.com/api/v2/channelsbyname/team/message' });
2167
- var tokenHint = el('p', { class: 'hint' });
2168
- var message = el('p', { role: 'status' });
2169
- var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save ' + title });
2170
- var test = el('button', { class: 'btn', type: 'button', text: 'Send test notification' });
2171
- var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
2172
- var photo = el('button', { class: 'btn ghost', type: 'button', text: 'Use the Heresay logo as the bot’s picture' });
2173
- var tg = telegram ? telegramGuide() : null;
2174
- var form = el('form', { class: 'form notification-form' }, telegram ? [
2175
- el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
2176
- setupStep(1, 'Make a bot', [
2177
- el('ol', { class: 'guide' }, [
2178
- el('li', {}, [el('a', { class: 'btn', href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener noreferrer', text: 'Open BotFather in Telegram ↗' })]),
2179
- el('li', {}, ['Send ', el('code', { text: '/newbot' }), '. It asks for a name (anything, like “Acme alerts”), then a username that ends in “bot” (like acme_alerts_bot).']),
2180
- el('li', {}, ['It replies with a long token that looks like ', el('code', { text: '123456789:AAH…' }), '. Copy it and paste it here.']),
2181
- ]),
2182
- el('label', {}, ['Bot token', token]), tokenHint, tg.botLine,
2183
- ]),
2184
- setupStep(2, 'Choose where alerts go', [tg.step2]),
2185
- setupStep(3, 'Save and test', [
2186
- el('p', { class: 'hint', text: 'Save, then send a test. It arrives from your bot in a few seconds.' }),
2187
- el('div', { class: 'row tight' }, [save, test, remove]), message,
2188
- el('div', { class: 'row tight' }, [photo, el('span', { class: 'hint', text: 'Replaces the bot’s current picture.' })]),
2189
- ]),
2190
- ] : [
2191
- el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
2192
- el('label', {}, ['Webhook token', token]), tokenHint,
2193
- el('label', {}, ['Message endpoint', address]),
2194
- el('p', { class: 'hint' }, ['In Cliq, open Bots & Tools → Webhook Tokens and generate a token. Use the bot or channel message endpoint from Get Webhook URL, without the ?zapikey part. Use your region’s Cliq domain. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Cliq setup guide' })]),
2195
- el('div', { class: 'row' }, [save, test, remove]), message,
2196
- ]);
2197
- /**
2198
- * Telegram has no screen that shows a chat ID, so we never ask for one up front. Once the
2199
- * token checks out, the person picks who gets alerts, follows two or three taps, and this
2200
- * page watches the bot until their chat turns up, then chooses it.
2201
- */
2202
- function telegramGuide() {
2203
- var g = { botLine: el('div', { class: 'bot-line', 'aria-live': 'polite' }), step2: el('div', { class: 'tg-step2' }) };
2204
- var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null, connected = false;
2205
- var KIND = { private: 'Private chat', group: 'Group', supergroup: 'Group', channel: 'Channel' };
2206
- var wait = el('div', { class: 'wait', role: 'status' });
2207
- var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
2208
- var chosen = el('p', { class: 'ok-msg chosen-line' });
2209
- var manual = el('details', { class: 'where', open: !!saved.chat_id }, [
2210
- el('summary', { text: 'Enter a chat ID yourself' }),
2211
- el('label', {}, ['Chat ID or channel username', address]),
2212
- el('p', { class: 'hint', text: 'Only if you already know it, like -1001234567890 or @yourchannel. Picking a chat above fills this in.' }),
2213
- ]);
2214
- var tabs = el('div', { class: 'seg', role: 'tablist', 'aria-label': 'Who gets alerts' });
2215
- var how = el('ol', { class: 'guide' });
2216
- var again = el('button', { class: 'btn', type: 'button', text: 'Look again', onclick: function () { watch(); } });
2217
-
2218
- function link(href, text) { return el('a', { class: 'btn', href: href, target: '_blank', rel: 'noopener noreferrer', text: text }); }
2219
- function drawHow() {
2220
- var at = '@' + bot.username, url = 'https://t.me/' + encodeURIComponent(bot.username);
2221
- how.textContent = '';
2222
- (kind === 'private' ? [
2223
- [link(url, 'Open ' + at + ' in Telegram ↗')],
2224
- ['Tap ', el('b', { text: 'Start' }), ' at the bottom of the chat. No Start button? Send it any message, like “hi”.'],
2225
- ['Come back to this page. It finds the chat by itself.'],
2226
- ] : kind === 'group' ? [
2227
- [link(url + '?startgroup=heresay', 'Add ' + at + ' to a group ↗')],
2228
- ['Telegram asks which group. Pick it and confirm.'],
2229
- ['Come back to this page. It finds the group by itself. If it doesn’t, send ', el('code', { text: '/start' + at }), ' in the group.'],
2230
- ] : [
2231
- ['In Telegram, open your channel and tap its name, then ', el('b', { text: 'Administrators' }), ' → ', el('b', { text: 'Add Admin' }), '.'],
2232
- ['Search for ', el('b', { text: at }), ', add it, and leave ', el('b', { text: 'Post Messages' }), ' on.'],
2233
- ['Post anything in the channel, then come back to this page. It finds the channel by itself.'],
2234
- ]).forEach(function (kids) { how.appendChild(el('li', {}, kids)); });
2235
- }
2236
- function drawTabs() {
2237
- tabs.textContent = '';
2238
- [['private', 'Just me'], ['group', 'A group'], ['channel', 'A channel']].forEach(function (t) {
2239
- tabs.appendChild(el('button', { type: 'button', role: 'tab', 'aria-selected': String(kind === t[0]), text: t[1], onclick: function () {
2240
- kind = t[0]; drawTabs(); drawHow(); drawChats(); watch();
2241
- } }));
2242
- });
2243
- }
2244
- function sameKind(c) { return kind === 'group' ? c.kind === 'group' || c.kind === 'supergroup' : c.kind === kind; }
2245
- function pick(c) {
2246
- address.value = c.id;
2247
- enabled.checked = true;
2248
- form.dispatchEvent(new Event('input'));
2249
- stop();
2250
- drawChats();
2251
- feedback('Chat chosen. Save to start sending alerts there.');
2252
- }
2253
- function drawChats() {
2254
- list.textContent = '';
2255
- var hit = chats.filter(function (c) { return c.id === address.value; })[0];
2256
- chosen.hidden = !address.value;
2257
- chosen.textContent = hit ? '✓ Alerts will go to ' + hit.title + ' (' + KIND[hit.kind].toLowerCase() + ').'
2258
- : address.value ? '✓ Alerts go to chat ' + address.value + '. Pick another below to change it.' : '';
2259
- chats.forEach(function (c) {
2260
- var radio = el('input', { type: 'radio', name: 'telegram_chat', value: c.id, checked: address.value === c.id });
2261
- radio.onchange = function () { pick(c); };
2262
- list.appendChild(el('label', { class: 'chat-choice' }, [radio, el('span', {}, [el('b', { text: c.title }), el('span', { class: 'mute', text: KIND[c.kind] })])]));
2263
- });
2264
- list.hidden = !chats.length;
2265
- }
2266
- function drawWait(state) {
2267
- wait.textContent = '';
2268
- wait.className = 'wait' + (state === 'idle' ? ' ok idle' : '');
2269
- if (state === 'waiting') wait.appendChild(document.createTextNode('Waiting for ' + (kind === 'private' ? 'your message to' : kind === 'group' ? 'a group with' : 'a channel with') + ' @' + bot.username + '…'));
2270
- else if (state === 'idle') { wait.appendChild(document.createTextNode('Nothing yet. Follow the steps above, then')); wait.appendChild(again); }
2271
- wait.hidden = state === 'none';
2272
- }
2273
- function stop() { clearTimeout(timer); timer = null; if (bot && !connected) drawWait(address.value ? 'none' : 'idle'); }
2274
- function watch() {
2275
- clearTimeout(timer);
2276
- until = Date.now() + 5 * 60 * 1000;
2277
- drawWait('waiting');
2278
- poll();
2279
- }
2280
- function poll() {
2281
- if (!form.isConnected) return;
2282
- lookup(true).then(function () {
2283
- var match = chats.filter(sameKind)[0];
2284
- if (match && !address.value) return pick(match); // never replace a chat they already chose
2285
- if (match) return stop();
2286
- if (Date.now() > until) return stop();
2287
- timer = setTimeout(poll, 6000);
2288
- }).catch(stop);
2289
- }
2290
- function lookup(quiet) {
2291
- return api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
2292
- var fresh = !bot || bot.username !== b.bot.username;
2293
- bot = b.bot; chats = b.chats; connected = !!b.connected;
2294
- g.botLine.textContent = '';
2295
- g.botLine.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ Token works. ' }), document.createTextNode('Your bot is ' + (bot.name || 'ready') + ' (@' + bot.username + ').')]));
2296
- if (fresh) { g.step2.textContent = ''; drawTabs(); drawHow(); [el('p', { class: 'hint', text: 'Who should get the alerts?' }), tabs, how, wait, list, chosen, manual].forEach(function (n) { g.step2.appendChild(n); }); }
2297
- drawChats();
2298
- if (b.note) g.botLine.appendChild(el('p', { class: 'hint', text: b.note }));
2299
- }).catch(function (x) {
2300
- if (quiet && bot) return;
2301
- g.botLine.textContent = '';
2302
- g.botLine.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
2303
- throw x;
2304
- });
2305
- }
2306
- function check() {
2307
- clearTimeout(checking);
2308
- checking = setTimeout(function () {
2309
- lookup().then(function () { if (!address.value && !connected) watch(); else stop(); }).catch(function () {});
2310
- }, 400);
2311
- }
2312
- g.step2.appendChild(el('p', { class: 'hint', text: 'Paste your bot token above first. Then this step shows exactly what to tap.' }));
2313
- g.step2.appendChild(manual);
2314
- token.addEventListener('input', function () { if (/^\d+:[A-Za-z0-9_-]{20,}$/.test(token.value.trim())) check(); });
2315
- if (saved.configured) check();
2316
- return g;
2317
- }
2318
- function refresh() {
2319
- token.placeholder = saved.configured ? 'Leave blank to keep the saved token' : 'Paste your token';
2320
- tokenHint.textContent = saved.configured ? 'A token is saved. Paste a new one to replace it.' : 'Your token is saved on the server and is never displayed here.';
2321
- test.disabled = dirty || !saved.enabled;
2322
- remove.disabled = !saved.configured;
2323
- photo.disabled = !saved.configured;
2324
- }
2325
- function busy(on) {
2326
- form.querySelectorAll('input, button').forEach(function (control) { control.disabled = on; });
2327
- if (!on) refresh();
2328
- }
2329
- function feedback(text, bad) { message.className = bad ? 'err' : 'ok-msg'; message.textContent = text; }
2330
- form.oninput = function () { dirty = true; test.disabled = true; feedback('Save your changes before sending a test.'); };
2331
- form.onsubmit = function (e) {
2332
- e.preventDefault();
2333
- var patch = { enabled: enabled.checked, token: token.value.trim() };
2334
- patch[telegram ? 'chat_id' : 'endpoint'] = address.value.trim();
2335
- var body = {}; body[provider] = patch;
2336
- busy(true); feedback('Saving…');
2337
- api('PATCH', '/notifications', body).then(function (result) {
2338
- saved = result.notifications[provider]; dirty = false; token.value = '';
2339
- feedback(title + ' settings saved. Send a test to check delivery.');
2340
- }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2341
- };
2342
- test.onclick = function () {
2343
- busy(true); feedback('Sending a test…');
2344
- api('POST', '/notifications/test', { provider: provider }).then(function () {
2345
- feedback('Test notification sent. Check ' + title + '.');
2346
- }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2347
- };
2348
- photo.onclick = function () {
2349
- busy(true); photo.textContent = 'Setting the picture…';
2350
- api('POST', '/notifications/telegram/photo', {}).then(function () {
2351
- toast('The bot now uses the Heresay logo. Telegram may take a moment to show it.');
2352
- }).catch(function (x) { toast(x.message, null, true); }).finally(function () {
2353
- photo.textContent = 'Use the Heresay logo as the bot’s picture'; busy(false);
2354
- });
2355
- };
2356
- remove.onclick = function () {
2357
- var body = {}, patch = { enabled: false, token: null };
2358
- patch[telegram ? 'chat_id' : 'endpoint'] = '';
2359
- body[provider] = patch;
2360
- busy(true); feedback('Disconnecting…');
2361
- api('PATCH', '/notifications', body).then(function (result) {
2362
- saved = result.notifications[provider]; dirty = false; enabled.checked = false; token.value = ''; address.value = '';
2363
- feedback(title + ' disconnected. The saved token was removed.');
2364
- }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2365
- };
2366
- refresh();
2367
- content.appendChild(el('section', { class: 'card' }, [el('h2', { text: title }), form]));
2368
- }
2133
+ content.appendChild(destinationModule('telegram', 'Telegram', settings.telegram));
2134
+ content.appendChild(destinationModule('cliq', 'Zoho Cliq', settings.cliq));
2135
+ content.appendChild(eventsModule(settings));
2369
2136
  }).catch(function (x) {
2137
+ content.textContent = '';
2370
2138
  content.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
2371
2139
  content.appendChild(el('button', { class: 'btn', text: 'Retry', onclick: function () { route(); } }));
2372
2140
  });
2373
2141
  }
2374
2142
 
2143
+ function statePill(saved) {
2144
+ return el('span', { class: 'pill-state' + (saved.configured && saved.enabled ? ' on' : ''), text: !saved.configured ? 'Not set up' : saved.enabled ? 'On' : 'Paused' });
2145
+ }
2146
+
2147
+ /** What to send: one switch per event, each saved the moment it is flipped. */
2148
+ function eventsModule(settings) {
2149
+ var choices = [
2150
+ ['new_report', 'New reports', 'waiting for review'],
2151
+ ['accepted', 'Accepted', 'sent to an agent'],
2152
+ ['fixed', 'Marked fixed', 'by a person or an agent'],
2153
+ ['handoff', 'Agent handoffs', 'to another repo'],
2154
+ ];
2155
+ var inputs = {}, saved = el('span', { class: 'saved-tick', role: 'status' });
2156
+ var rows = choices.map(function (c) {
2157
+ var input = inputs[c[0]] = el('input', { type: 'checkbox', class: 'switch', name: c[0], checked: settings.events[c[0]] });
2158
+ input.onchange = function () {
2159
+ var events = {};
2160
+ Object.keys(inputs).forEach(function (k) { events[k] = inputs[k].checked; });
2161
+ saved.textContent = 'Saving…';
2162
+ api('PATCH', '/notifications', { events: events }).then(function () { saved.textContent = '✓ Saved'; })
2163
+ .catch(function (x) { input.checked = !input.checked; saved.textContent = ''; toast(x.message, null, true); });
2164
+ };
2165
+ return el('label', { class: 'switch-row' }, [el('span', {}, [el('b', { text: c[1] }), el('span', { class: 'hint', text: ' ' + c[2] })]), input]);
2166
+ });
2167
+ return el('section', { class: 'card module' }, [
2168
+ el('div', { class: 'module-head' }, [el('h2', { text: 'What to send' }), el('span', { class: 'spacer' }), saved]),
2169
+ el('div', {}, rows),
2170
+ el('p', { class: 'hint', text: 'Alerts show the app and a link. Never the report text.' }),
2171
+ ]);
2172
+ }
2173
+
2174
+ /**
2175
+ * One place alerts can go. Closed, it is a name, a state, an on/off switch and a test button; Set up or Edit opens the
2176
+ * form. Telegram's form is three short steps; Cliq's is two fields.
2177
+ */
2178
+ function destinationModule(provider, title, saved) {
2179
+ var telegram = provider === 'telegram', dirty = false, opened = false;
2180
+ var addrKey = telegram ? 'chat_id' : 'endpoint';
2181
+ var enabled = { checked: saved.enabled };
2182
+ var token = el('input', { type: 'password', name: provider + '_token', maxlength: 512, autocomplete: 'new-password', spellcheck: 'false' });
2183
+ var address = el('input', { type: 'text', name: addrKey, value: saved[addrKey], maxlength: telegram ? 100 : 300, autocomplete: 'off', spellcheck: 'false', placeholder: telegram ? '-1001234567890 or @yourchannel' : 'https://cliq.zoho.com/api/v2/channelsbyname/team/message' });
2184
+ var tokenHint = el('p', { class: 'hint' });
2185
+ var message = el('p', { role: 'status' });
2186
+ var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save' });
2187
+ var test = el('button', { class: 'btn', type: 'button', text: 'Send test' });
2188
+ var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
2189
+ var photo = el('button', { class: 'btn ghost', type: 'button', text: 'Use the Heresay logo as the bot’s picture' });
2190
+ var sw = el('input', { type: 'checkbox', class: 'switch', name: provider + '_enabled', 'aria-label': title + ' alerts on', checked: saved.enabled });
2191
+ var head = el('div', { class: 'module-head' });
2192
+ var edit = el('button', { class: 'btn', type: 'button', 'aria-expanded': 'false' });
2193
+ var panel = el('div', { class: 'module-panel', hidden: true });
2194
+ var tg = telegram ? telegramGuide() : null;
2195
+ var form = el('form', { class: 'form notification-form' }, telegram ? [
2196
+ setupStep(1, 'Make a bot', [
2197
+ el('p', {}, [el('a', { class: 'btn', href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener noreferrer', text: 'Open BotFather ↗' }), ' Send ', el('code', { text: '/newbot' }), ', then paste the token it gives you.']),
2198
+ el('label', {}, ['Bot token', token]), tokenHint, tg.botLine,
2199
+ ]),
2200
+ setupStep(2, 'Pick the chat', [tg.step2]),
2201
+ el('div', { class: 'row tight' }, [save]), message,
2202
+ ] : [
2203
+ el('label', {}, ['Webhook token', token]), tokenHint,
2204
+ el('label', {}, ['Message endpoint', address]),
2205
+ el('p', { class: 'hint' }, ['In Cliq: Bots & Tools → Webhook Tokens. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Guide ↗' })]),
2206
+ el('div', { class: 'row tight' }, [save]), message,
2207
+ ]);
2208
+ var more = el('div', { class: 'row tight module-more' }, telegram ? [photo, remove] : [remove]);
2209
+ panel.appendChild(form); panel.appendChild(more);
2210
+ var actions = el('div', { class: 'module-row' }, [el('span', { class: 'grow' }), test, edit]);
2211
+ var box = el('section', { class: 'card module' }, [head, actions, panel]);
2212
+ if (telegram) box.insertBefore(telegramLink({ turnOn: function () { return saveSettings({ enabled: true }); }, saved: function () { return saved; } }), panel);
2213
+
2214
+ /**
2215
+ * Telegram has no screen that shows a chat ID, so we never ask for one up front. Once the
2216
+ * token checks out, the person picks who gets alerts, follows two or three taps, and this
2217
+ * page watches the bot until their chat turns up, then chooses it.
2218
+ */
2219
+ function telegramGuide() {
2220
+ var g = { botLine: el('div', { class: 'bot-line', 'aria-live': 'polite' }), step2: el('div', { class: 'tg-step2' }), start: function () { if (saved.configured) check(); } };
2221
+ var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null, connected = false;
2222
+ var KIND = { private: 'Private chat', group: 'Group', supergroup: 'Group', channel: 'Channel' };
2223
+ var wait = el('div', { class: 'wait', role: 'status' });
2224
+ var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
2225
+ var chosen = el('p', { class: 'ok-msg chosen-line' });
2226
+ var manual = el('details', { class: 'where', open: !!saved.chat_id }, [
2227
+ el('summary', { text: 'Enter a chat ID' }),
2228
+ el('label', {}, ['Chat ID or channel username', address]),
2229
+ ]);
2230
+ var tabs = el('div', { class: 'seg', role: 'tablist', 'aria-label': 'Who gets alerts' });
2231
+ var how = el('ol', { class: 'guide' });
2232
+ var again = el('button', { class: 'btn', type: 'button', text: 'Look again', onclick: function () { watch(); } });
2233
+
2234
+ function link(href, text) { return el('a', { class: 'btn', href: href, target: '_blank', rel: 'noopener noreferrer', text: text }); }
2235
+ function drawHow() {
2236
+ var at = '@' + bot.username, url = 'https://t.me/' + encodeURIComponent(bot.username);
2237
+ how.textContent = '';
2238
+ (kind === 'private' ? [
2239
+ [link(url, 'Open ' + at + ' in Telegram ↗')],
2240
+ ['Tap ', el('b', { text: 'Start' }), ' (or send “hi”). This page finds the chat.'],
2241
+ ] : kind === 'group' ? [
2242
+ [link(url + '?startgroup=heresay', 'Add ' + at + ' to a group ↗')],
2243
+ ['Pick the group. This page finds it. Not found? Send ', el('code', { text: '/start' + at }), ' in the group.'],
2244
+ ] : [
2245
+ ['Channel → ', el('b', { text: 'Administrators' }), ' → ', el('b', { text: 'Add Admin' }), ' → ', el('b', { text: at }), '.'],
2246
+ ['Post anything in the channel. This page finds it.'],
2247
+ ]).forEach(function (kids) { how.appendChild(el('li', {}, kids)); });
2248
+ }
2249
+ function drawTabs() {
2250
+ tabs.textContent = '';
2251
+ [['private', 'Just me'], ['group', 'A group'], ['channel', 'A channel']].forEach(function (t) {
2252
+ tabs.appendChild(el('button', { type: 'button', role: 'tab', 'aria-selected': String(kind === t[0]), text: t[1], onclick: function () {
2253
+ kind = t[0]; drawTabs(); drawHow(); drawChats(); watch();
2254
+ } }));
2255
+ });
2256
+ }
2257
+ function sameKind(c) { return kind === 'group' ? c.kind === 'group' || c.kind === 'supergroup' : c.kind === kind; }
2258
+ function pick(c) {
2259
+ address.value = c.id;
2260
+ enabled.checked = true;
2261
+ form.dispatchEvent(new Event('input'));
2262
+ stop();
2263
+ drawChats();
2264
+ feedback('Chat chosen. Save to start sending alerts there.');
2265
+ }
2266
+ function drawChats() {
2267
+ list.textContent = '';
2268
+ var hit = chats.filter(function (c) { return c.id === address.value; })[0];
2269
+ chosen.hidden = !address.value;
2270
+ chosen.textContent = hit ? '✓ Alerts will go to ' + hit.title + ' (' + KIND[hit.kind].toLowerCase() + ').'
2271
+ : address.value ? '✓ Alerts go to chat ' + address.value + '. Pick another below to change it.' : '';
2272
+ chats.forEach(function (c) {
2273
+ var radio = el('input', { type: 'radio', name: 'telegram_chat', value: c.id, checked: address.value === c.id });
2274
+ radio.onchange = function () { pick(c); };
2275
+ list.appendChild(el('label', { class: 'chat-choice' }, [radio, el('span', {}, [el('b', { text: c.title }), el('span', { class: 'mute', text: KIND[c.kind] })])]));
2276
+ });
2277
+ list.hidden = !chats.length;
2278
+ }
2279
+ function drawWait(state) {
2280
+ wait.textContent = '';
2281
+ wait.className = 'wait' + (state === 'idle' ? ' ok idle' : '');
2282
+ if (state === 'waiting') wait.appendChild(document.createTextNode('Waiting for ' + (kind === 'private' ? 'your message to' : kind === 'group' ? 'a group with' : 'a channel with') + ' @' + bot.username + '…'));
2283
+ else if (state === 'idle') { wait.appendChild(document.createTextNode('Nothing yet.')); wait.appendChild(again); }
2284
+ wait.hidden = state === 'none';
2285
+ }
2286
+ function stop() { clearTimeout(timer); timer = null; if (bot && !connected) drawWait(address.value ? 'none' : 'idle'); }
2287
+ function watch() {
2288
+ clearTimeout(timer);
2289
+ until = Date.now() + 5 * 60 * 1000;
2290
+ drawWait('waiting');
2291
+ poll();
2292
+ }
2293
+ function poll() {
2294
+ if (!form.isConnected) return;
2295
+ lookup(true).then(function () {
2296
+ var match = chats.filter(sameKind)[0];
2297
+ if (match && !address.value) return pick(match); // never replace a chat they already chose
2298
+ if (match) return stop();
2299
+ if (Date.now() > until) return stop();
2300
+ timer = setTimeout(poll, 6000);
2301
+ }).catch(stop);
2302
+ }
2303
+ function lookup(quiet) {
2304
+ return api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
2305
+ var fresh = !bot || bot.username !== b.bot.username;
2306
+ bot = b.bot; chats = b.chats; connected = !!b.connected;
2307
+ g.botLine.textContent = '';
2308
+ g.botLine.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ Token works. ' }), document.createTextNode('Your bot is ' + (bot.name || 'ready') + ' (@' + bot.username + ').')]));
2309
+ if (fresh) { g.step2.textContent = ''; drawTabs(); drawHow(); [tabs, how, wait, list, chosen, manual].forEach(function (n) { g.step2.appendChild(n); }); }
2310
+ drawChats();
2311
+ if (b.note) g.botLine.appendChild(el('p', { class: 'hint', text: b.note }));
2312
+ }).catch(function (x) {
2313
+ if (quiet && bot) return;
2314
+ g.botLine.textContent = '';
2315
+ g.botLine.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
2316
+ throw x;
2317
+ });
2318
+ }
2319
+ function check() {
2320
+ clearTimeout(checking);
2321
+ checking = setTimeout(function () {
2322
+ lookup().then(function () { if (!address.value && !connected) watch(); else stop(); }).catch(function () {});
2323
+ }, 400);
2324
+ }
2325
+ g.step2.appendChild(el('p', { class: 'hint', text: 'Paste the bot token first.' }));
2326
+ g.step2.appendChild(manual);
2327
+ token.addEventListener('input', function () { if (/^\d+:[A-Za-z0-9_-]{20,}$/.test(token.value.trim())) check(); });
2328
+ return g;
2329
+ }
2330
+
2331
+ function draw() {
2332
+ head.textContent = '';
2333
+ head.appendChild(el('h2', { text: title }));
2334
+ head.appendChild(statePill(saved));
2335
+ head.appendChild(el('span', { class: 'spacer' }));
2336
+ if (saved.configured) head.appendChild(sw);
2337
+ sw.checked = enabled.checked = !!saved.enabled;
2338
+ tokenHint.textContent = saved.configured ? 'A token is saved. Paste a new one to replace it.' : 'Kept on the server, never shown here.';
2339
+ token.placeholder = saved.configured ? 'Leave blank to keep it' : 'Paste your token';
2340
+ test.hidden = !saved.configured; test.disabled = dirty || !saved.enabled;
2341
+ remove.disabled = !saved.configured; photo.disabled = !saved.configured;
2342
+ more.hidden = !saved.configured;
2343
+ edit.textContent = opened ? 'Close' : saved.configured ? 'Edit' : 'Set up';
2344
+ edit.classList.toggle('primary', !saved.configured && !opened);
2345
+ edit.setAttribute('aria-expanded', String(opened));
2346
+ panel.hidden = !opened;
2347
+ actions.querySelector('.grow').textContent = saved.configured && !opened ? (saved.enabled ? (telegram ? 'Alerts go to your chat.' : 'Alerts go to your channel.') : 'Paused. Flip the switch to resume.') : (saved.configured ? '' : 'Not set up.');
2348
+ }
2349
+ function busy(on) {
2350
+ box.querySelectorAll('input, button').forEach(function (control) { control.disabled = on; });
2351
+ if (!on) draw();
2352
+ }
2353
+ function feedback(text, bad) { message.className = bad ? 'err' : 'ok-msg'; message.textContent = text; }
2354
+ /** A save with the fields that matter here; a blank token means keep the saved one. */
2355
+ function saveSettings(patch) {
2356
+ var body = {}; body[provider] = Object.assign({ enabled: enabled.checked, token: '' }, patch);
2357
+ if (body[provider][addrKey] === undefined) body[provider][addrKey] = saved[addrKey] || '';
2358
+ return api('PATCH', '/notifications', body).then(function (result) { saved = result.notifications[provider]; return result; });
2359
+ }
2360
+ edit.onclick = function () { opened = !opened; if (opened && telegram && !tg.started) { tg.started = true; tg.start(); } draw(); };
2361
+ sw.onchange = function () {
2362
+ var on = sw.checked;
2363
+ busy(true);
2364
+ saveSettings({ enabled: on }).then(function () { enabled.checked = on; toast(title + (on ? ' alerts are on.' : ' alerts are paused.')); })
2365
+ .catch(function (x) { sw.checked = !on; toast(x.message, null, true); }).finally(function () { busy(false); });
2366
+ };
2367
+ form.oninput = function () { dirty = true; test.disabled = true; feedback('Save, then send a test.'); };
2368
+ form.onsubmit = function (e) {
2369
+ e.preventDefault();
2370
+ var patch = { enabled: true, token: token.value.trim() };
2371
+ patch[addrKey] = address.value.trim();
2372
+ busy(true); feedback('Saving…');
2373
+ var body = {}; body[provider] = patch;
2374
+ api('PATCH', '/notifications', body).then(function (result) {
2375
+ saved = result.notifications[provider]; dirty = false; token.value = ''; enabled.checked = true;
2376
+ feedback('Saved. Send a test to check it.');
2377
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2378
+ };
2379
+ test.onclick = function () {
2380
+ busy(true);
2381
+ api('POST', '/notifications/test', { provider: provider }).then(function () {
2382
+ toast('Test sent. Check ' + title + '.'); feedback('Test sent. Check ' + title + '.');
2383
+ }).catch(function (x) { toast(x.message, null, true); feedback(x.message, true); }).finally(function () { busy(false); });
2384
+ };
2385
+ photo.onclick = function () {
2386
+ busy(true); photo.textContent = 'Setting the picture…';
2387
+ api('POST', '/notifications/telegram/photo', {}).then(function () {
2388
+ toast('The bot now uses the Heresay logo. Telegram may take a moment to show it.');
2389
+ }).catch(function (x) { toast(x.message, null, true); }).finally(function () {
2390
+ photo.textContent = 'Use the Heresay logo as the bot’s picture'; busy(false);
2391
+ });
2392
+ };
2393
+ remove.onclick = function () {
2394
+ var patch = { enabled: false, token: null }; patch[addrKey] = '';
2395
+ var body = {}; body[provider] = patch;
2396
+ busy(true); feedback('Disconnecting…');
2397
+ api('PATCH', '/notifications', body).then(function (result) {
2398
+ saved = result.notifications[provider]; dirty = false; enabled.checked = false; token.value = ''; address.value = '';
2399
+ opened = false; toast(title + ' disconnected.');
2400
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2401
+ };
2402
+ draw();
2403
+ return box;
2404
+ }
2405
+
2375
2406
  /**
2376
2407
  * Tapping Accept or Decline in Telegram only counts for someone who linked their Telegram to their
2377
- * own sign-in: a one-time code, sent to the bot. Any member can do this; it isn't owner-only.
2408
+ * own sign-in: a one-time code, sent to the bot. Any member can do this; it isn't owner-only. A row inside
2409
+ * the Telegram module for owners, a module of its own for everyone else. `turnOn` (owners): save Telegram again,
2410
+ * which puts the buttons on the bot.
2378
2411
  */
2379
- function telegramActions(host) {
2380
- var body = el('div', {}, [loading()]);
2381
- host.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'Act from Telegram' }), body]));
2412
+ function telegramLink(opts) {
2413
+ var body = el('div', { class: 'module-row link-row' }, [loading()]);
2382
2414
  draw();
2383
2415
  function draw() {
2384
2416
  api('GET', '/telegram/link').then(function (b) {
2385
2417
  body.textContent = '';
2418
+ var msg = el('p', { role: 'status', class: 'grow-line' }), shown = el('div', { class: 'link-code' });
2419
+ var line = el('span', { class: 'grow' });
2420
+ body.appendChild(line);
2386
2421
  if (!b.connected) {
2387
- body.appendChild(el('p', { class: 'hint', text: 'Not connected. Once an owner connects a Telegram bot above and this Heresay has a public https address, new-report alerts get Accept and Decline buttons and you can use them after linking your Telegram here.' }));
2422
+ var s = opts.saved && opts.saved();
2423
+ line.textContent = 'Accept and decline buttons: off.';
2424
+ if (opts.turnOn && s && s.configured && s.enabled) {
2425
+ var on = el('button', { class: 'btn primary', type: 'button', text: 'Turn on' });
2426
+ on.onclick = function () {
2427
+ var done = busyButton(on, 'Turning on…');
2428
+ opts.turnOn().then(function () { draw(); }).catch(function (x) { msg.className = 'err'; msg.textContent = x.message; done(); });
2429
+ };
2430
+ body.appendChild(on);
2431
+ } else if (!opts.turnOn) line.textContent = 'Accept and decline buttons appear once an owner connects Telegram.';
2432
+ body.appendChild(msg);
2388
2433
  return;
2389
2434
  }
2390
- var msg = el('p', { role: 'status' }), shown = el('div', {});
2391
- var make = el('button', { class: 'btn' + (b.linked ? '' : ' primary'), type: 'button', text: b.linked ? 'Make a new code' : 'Link my Telegram' });
2435
+ line.textContent = b.linked ? '✓ You can accept and decline from Telegram.' : 'Accept and decline from Telegram.';
2436
+ line.className = 'grow' + (b.linked ? ' ok-msg' : '');
2437
+ var make = el('button', { class: 'btn' + (b.linked ? '' : ' primary'), type: 'button', text: b.linked ? 'New code' : 'Link my Telegram' });
2392
2438
  make.onclick = function () {
2393
2439
  var done = busyButton(make, 'Making a code…');
2394
2440
  api('POST', '/telegram/link-code', {}).then(function (c) {
2395
2441
  var at = c.bot_username ? '@' + c.bot_username : 'your Heresay bot';
2396
2442
  shown.textContent = '';
2397
2443
  shown.appendChild(codeBlock('/start ' + c.code));
2398
- shown.appendChild(el('p', {}, ['Send ', el('code', { text: '/start ' + c.code }), ' to ' + at + ', in a private chat or in the alerts group. This code works once and expires ',
2399
- el('b', { text: 'at ' + new Date(c.expires_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) }), '.']));
2400
- if (c.bot_username) shown.appendChild(el('a', { class: 'btn', href: 'https://t.me/' + encodeURIComponent(c.bot_username) + '?start=' + encodeURIComponent(c.code), target: '_blank', rel: 'noopener noreferrer', text: 'Open ' + at + ' in Telegram ↗' }));
2444
+ shown.appendChild(el('p', {}, ['Send it to ' + at + '. Works once, until ',
2445
+ el('b', { text: new Date(c.expires_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) }), '.']));
2446
+ if (c.bot_username) shown.appendChild(el('a', { class: 'btn', href: 'https://t.me/' + encodeURIComponent(c.bot_username) + '?start=' + encodeURIComponent(c.code), target: '_blank', rel: 'noopener noreferrer', text: 'Open ' + at + ' ↗' }));
2401
2447
  msg.textContent = '';
2402
2448
  }).catch(function (x) { msg.className = 'err'; msg.textContent = x.message; }).finally(done);
2403
2449
  };
2404
- var kids = [
2405
- el('p', { class: b.linked ? 'ok-msg' : 'hint', text: b.linked
2406
- ? '✓ Your Telegram is linked. You can accept or decline reports from the alerts. Decline asks you for the reason, which the reporter reads.'
2407
- : 'Link your Telegram to accept or decline reports from the alerts. Only linked team members can; anyone else’s tap is refused.' }),
2408
- el('div', { class: 'row' }, [make]),
2409
- ];
2450
+ body.appendChild(make);
2410
2451
  if (b.linked) {
2411
2452
  var unlink = el('button', { class: 'btn ghost', type: 'button', text: 'Unlink' });
2412
2453
  unlink.onclick = function () {
@@ -2414,12 +2455,12 @@
2414
2455
  api('DELETE', '/telegram/link').then(function () { toast('Your Telegram is unlinked.'); draw(); })
2415
2456
  .catch(function (x) { msg.className = 'err'; msg.textContent = x.message; done(); });
2416
2457
  };
2417
- kids[1].appendChild(unlink);
2458
+ body.appendChild(unlink);
2418
2459
  }
2419
- kids.push(shown, msg);
2420
- kids.forEach(function (k) { body.appendChild(k); });
2460
+ body.appendChild(msg); body.appendChild(shown);
2421
2461
  }).catch(function (x) { body.textContent = ''; body.appendChild(el('p', { class: 'err', role: 'alert', text: x.message })); });
2422
2462
  }
2463
+ return body;
2423
2464
  }
2424
2465
 
2425
2466
  // ---- team ------------------------------------------------------------------------------