domma-cms 1.80.0 → 1.81.0

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/admin/css/site-settings.css +1 -1
  3. package/admin/js/lib/site-settings-arrange.js +3 -3
  4. package/admin/js/templates/docs/usage-site-settings.html +29 -3
  5. package/admin/js/templates/settings.html +94 -4
  6. package/admin/js/views/settings.js +3 -3
  7. package/docs/DommaFeatures.md +51 -2
  8. package/docs/plans/2026-11-19-brand-kit-design.md +1 -1
  9. package/docs/plugin-development.md +6 -0
  10. package/package.json +1 -1
  11. package/plugins/_lib/telegram/bot.js +120 -0
  12. package/plugins/free-tier.lock.json +26 -1
  13. package/plugins/telegram/CHANGELOG.md +5 -0
  14. package/plugins/telegram/CLAUDE.md +77 -0
  15. package/plugins/telegram/admin/css/index.css +68 -0
  16. package/plugins/telegram/admin/lib/arrange.js +103 -0
  17. package/plugins/telegram/admin/lib/kit.js +153 -0
  18. package/plugins/telegram/admin/templates/telegram.html +1 -0
  19. package/plugins/telegram/admin/views/chats.js +223 -0
  20. package/plugins/telegram/admin/views/connection.js +90 -0
  21. package/plugins/telegram/admin/views/telegram.js +89 -0
  22. package/plugins/telegram/admin/views/test.js +84 -0
  23. package/plugins/telegram/config.js +21 -0
  24. package/plugins/telegram/docs/guide.md +87 -0
  25. package/plugins/telegram/lib/messages.js +176 -0
  26. package/plugins/telegram/lib/queue.js +72 -0
  27. package/plugins/telegram/plugin.js +490 -0
  28. package/plugins/telegram/plugin.json +71 -0
  29. package/plugins/telegram/tests/api.test.js +381 -0
  30. package/plugins/telegram/tests/arrange.test.js +41 -0
  31. package/plugins/telegram/tests/messages.test.js +110 -0
  32. package/plugins/telegram/tests/queue.test.js +47 -0
  33. package/server/routes/api/brand-kit.js +55 -0
  34. package/server/routes/api/settings.js +17 -1
  35. package/server/server.js +2 -0
  36. package/server/services/brandKit.js +268 -0
  37. package/server/services/emailBrand.js +31 -13
  38. package/server/services/notify.js +20 -2
  39. package/server/services/plugins.js +3 -0
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Telegram › Chats - the linked chats and what each gets.
3
+ *
4
+ * A chat is linked from Telegram itself: the admin makes a one-time code here, someone sends "/link <code>" in
5
+ * the chat (a group with the bot added, or a private chat with the bot), and the chat appears in the list.
6
+ * Click a row (or Enter) for its routing; right-click, the kebab or Shift+F10 for the rest (test, pause, unlink).
7
+ *
8
+ * The routing panel is a bound slideover: closing it with changes asks first, and leaving the screen keeps the
9
+ * changes as a draft (per browser), offered back when that chat is opened again.
10
+ */
11
+ import {api, copy, drafts, esc, openPanel, wireRows} from '../lib/kit.js';
12
+ import {chatRow, linkView, routingBody, routingDraft, routingPrint, severityLabel} from '../lib/arrange.js';
13
+
14
+ const ROW = `
15
+ <div class="tg-row" data-id="{{id}}" tabindex="0" role="button" data-bind-title="title">
16
+ <span class="tg-chip">{{type}}</span>
17
+ <span class="tg-main"><strong>{{name}}</strong><small>{{alerts}} · {{forms}}</small><small>{{owner}}</small><small class="is-bad" data-bind-hidden="!problem">{{problem}}</small></span>
18
+ <span class="tg-chip is-warn" data-bind-hidden="!paused">Paused</span>
19
+ <button type="button" class="tg-kebab" aria-label="Chat actions" title="Actions">⋮</button>
20
+ </div>`;
21
+
22
+ const DRAFT = (id) => `telegram.draft.chat.${id}`;
23
+
24
+ export async function mount(root, ctx) {
25
+ const {kit, scope, here, status} = ctx;
26
+ const rows = M.observable([]);
27
+ const link = M.observable(linkView(status.peek()));
28
+ const s = () => status.peek() || {};
29
+ const manage = Boolean(s().can?.manage);
30
+ const connected = M.observable(Boolean(s().connected));
31
+ const botAt = M.observable('');
32
+ const making = M.observable(false);
33
+ const stop = M.effect(() => {
34
+ const st = status.value || {};
35
+ rows.value = (st.chats || []).map(c => chatRow(c, st));
36
+ link.value = linkView(st);
37
+ connected.value = Boolean(st.connected);
38
+ botAt.value = st.botName ? `@${st.botName}` : '';
39
+ });
40
+
41
+ root.innerHTML = `<div class="tg-stack">
42
+ <p class="tg-note is-warn" data-bind-hidden="connected.value">Connect the bot first, on the <a href="#/plugins/telegram">Connection</a> tab.</p>
43
+ <section class="tg-card" data-bind-hidden="!connected.value">
44
+ <header><h3><span data-icon="users" data-icon-size="16"></span> Linked chats <span data-help-title="Linked chats" data-help="Each chat linked here gets messages from the site: a group (your team's) or a private chat with the bot (one person's). Each has its own choice of alerts and forms - click a chat to change it. Only a chat linked with a code from this screen ever gets anything."></span></h3>
45
+ ${manage ? '<button type="button" class="btn btn-sm btn-primary" data-on-click="code" data-bind-disabled="making.value"><span data-icon="plus" data-icon-size="13"></span> Link a chat</button>' : ''}</header>
46
+
47
+ <div class="tg-note is-warn" data-bind-hidden="!link.value.code">
48
+ <ol class="tg-steps">
49
+ <li>In Telegram, add <b data-bind-text="botAt.value"></b> to the group (or open a private chat with it).</li>
50
+ <li>Send this in that chat: <code class="tg-code" data-bind-text="link.value.line"></code> <button type="button" class="btn btn-xs btn-ghost" data-on-click="copyCode">Copy</button></li>
51
+ <li>Click <b>Check</b>. The code works once, for 15 minutes.</li>
52
+ </ol>
53
+ <div class="tg-bar"><button type="button" class="btn btn-sm btn-primary" data-on-click="check">Check</button>
54
+ <span data-help="Anyone in a chat linked with this code reads what is routed to it, so send it only in a chat your team trusts. A few wrong codes in a row cancel it; make another one here."></span></div>
55
+ </div>
56
+
57
+ <div class="tg-empty" data-bind-hidden="rows.value.length"><h3><span data-icon="message-circle" data-icon-size="18"></span> No chats yet</h3>
58
+ <p>Link your team's Telegram group, or your own chat with the bot, and the site's warnings and form submissions arrive there.</p></div>
59
+ <div class="tg-list" data-bind-hidden="!rows.value.length" data-each="rows.value key=id"></div>
60
+ </section></div>`;
61
+ const view = root.firstElementChild;
62
+ const list = view.querySelector('.tg-list');
63
+ list.innerHTML = ROW;
64
+ scope(kit.helpPopovers(view, {position: 'bottom'}));
65
+ I.scan(view);
66
+
67
+ const panels = new Map();
68
+ scope(() => { for (const p of panels.values()) p.leave(); panels.clear(); });
69
+
70
+ const run = async (fn, said) => {
71
+ try {
72
+ const next = await fn();
73
+ ctx.take(next);
74
+ if (said && here()) E.toast(said, {type: 'success'});
75
+ return next;
76
+ } catch (err) { E.toast(err.message || String(err), {type: 'error'}); return null; }
77
+ };
78
+ const chat = (id) => (s().chats || []).find(c => c.id === id);
79
+
80
+ async function test(id) {
81
+ try { await api.test({chat: id, kind: 'hello'}); E.toast('Sent - look in that chat.', {type: 'success'}); } catch (err) { E.toast(err.message || String(err), {type: 'error'}); }
82
+ }
83
+ async function unlink(id) {
84
+ const c = chat(id);
85
+ if (!c) return;
86
+ const ok = await E.confirm(`Unlink <b>${esc(c.name)}</b>? It stops getting messages from the site, and the chat is told so.`,
87
+ {title: 'Unlink the chat', confirmText: 'Unlink', cancelText: 'Keep it'});
88
+ if (ok && here()) await run(() => api.unlink(id), 'Unlinked.');
89
+ }
90
+ const pause = (id) => { const c = chat(id); if (c) run(() => api.saveChat(id, {paused: !c.paused}), c.paused ? 'Resumed.' : 'Paused - nothing is sent there until you resume it.'); };
91
+
92
+ async function edit(id) {
93
+ const c = chat(id);
94
+ if (!c || panels.has(id)) return;
95
+ if (!manage) { E.toast('Only an administrator can change what a chat gets.', {type: 'info'}); return; }
96
+ const st = s();
97
+ const loaded = routingDraft(c, st);
98
+ let start = loaded;
99
+ const kept = drafts.get(DRAFT(id));
100
+ if (kept?.values && routingPrint(kept.values) !== routingPrint(loaded)) {
101
+ const use = await E.confirm(`You left changes to <b>${esc(c.name)}</b> unsaved. Use them?`, {title: 'Unsaved changes', confirmText: 'Use them', cancelText: 'Throw them away'});
102
+ if (!here()) return;
103
+ if (use) start = {...loaded, ...kept.values};
104
+ }
105
+ drafts.drop(DRAFT(id));
106
+
107
+ const name = M.observable(start.name);
108
+ const alertsOn = M.observable(start.alertsOn);
109
+ const sev = Object.fromEntries(Object.entries(start.severities).map(([k, v]) => [k, M.observable(v)]));
110
+ const allSources = M.observable(start.allSources);
111
+ const sources = (st.sources || []).map(x => ({id: x.id, label: x.label, group: x.ownerLabel, on: M.observable(Boolean(start.sources[x.id]))}));
112
+ const formsOn = M.observable(start.formsOn);
113
+ const allForms = M.observable(start.allForms);
114
+ const forms = (st.forms || []).map(f => ({id: f.slug, label: f.title, on: M.observable(Boolean(start.forms[f.slug]))}));
115
+ const detail = M.observable(start.detail);
116
+ const saving = M.observable(false);
117
+ const values = () => ({
118
+ name: name.peek(), alertsOn: alertsOn.peek(),
119
+ severities: Object.fromEntries(Object.entries(sev).map(([k, o]) => [k, o.peek()])),
120
+ allSources: allSources.peek(), sources: Object.fromEntries(sources.map(x => [x.id, x.on.peek()])),
121
+ formsOn: formsOn.peek(), allForms: allForms.peek(), forms: Object.fromEntries(forms.map(f => [f.id, f.on.peek()])),
122
+ detail: detail.peek()
123
+ });
124
+ const was = routingPrint(loaded);
125
+ const dirty = () => routingPrint(values()) !== was;
126
+
127
+ const html = `<div class="tg-panel">
128
+ <label class="form-label" for="tg-chat-name">Name in this admin <span data-help="Only for you: how this chat is listed here. Telegram does not see it."></span></label>
129
+ <input id="tg-chat-name" class="form-input" maxlength="80" data-model="name.value">
130
+
131
+ <fieldset><legend><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="alertsOn.value"> Alerts</label>
132
+ <span data-help-title="Alerts" data-help="The notifications the site raises in the bell - a payment failed, the disk is filling, a Tool stopped. Choose how serious they must be, and from which Tools. Notifications meant for one named person (a to-do reminder) are never sent to a chat."></span></legend>
133
+ <div data-bind-hidden="!alertsOn.value" class="tg-stack">
134
+ <div class="tg-bar">${Object.keys(sev).map(k => `<label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="sev.${k}.value"> ${severityLabel(k)}</label>`).join('')}</div>
135
+ <label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="allSources.value"> From every Tool</label>
136
+ <div class="tg-checks" data-bind-hidden="allSources.value" data-each="sourceList.value key=id"><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="on.value"> <span>{{label}} <small>{{group}}</small></span></label></div>
137
+ </div>
138
+ </fieldset>
139
+
140
+ <fieldset><legend><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="formsOn.value"> Form submissions</label>
141
+ <span data-help-title="Form submissions" data-help="Each time a visitor sends one of the chosen forms, this chat gets a message with the form's title and a link to its submissions. Passwords, files, images and hidden fields are never sent."></span></legend>
142
+ <div data-bind-hidden="!formsOn.value" class="tg-stack">
143
+ <label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="allForms.value"> Every form, including new ones</label>
144
+ <div class="tg-checks" data-bind-hidden="allForms.value" data-each="formList.value key=id"><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="on.value"> <span>{{label}}</span></label></div>
145
+ <p class="tg-note" data-bind-hidden="allForms.value || formList.value.length">There are no forms on this site yet.</p>
146
+ <label class="form-label">What the message holds <span data-help="With the answers: each question and what the visitor typed, so the team can act from Telegram. Title and link only: just which form was sent, with a link to read it in the admin - nothing the visitor typed leaves the site."></span></label>
147
+ <label class="tg-check"><input type="radio" name="tg-detail" value="fields" data-model="detail.value"> The form's title, the answers and a link</label>
148
+ <label class="tg-check"><input type="radio" name="tg-detail" value="title" data-model="detail.value"> The form's title and a link only</label>
149
+ </div>
150
+ </fieldset>
151
+
152
+ <div class="tg-actions">
153
+ <span class="tg-spacer"></span>
154
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
155
+ <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="saving.value">Save</button>
156
+ </div>
157
+ </div>`;
158
+ let panel = null;
159
+ const entry = {
160
+ /** The screen has gone: keep the changes as a draft, close without asking. */
161
+ leave() { if (dirty()) drafts.set(DRAFT(id), {values: values(), at: Date.now()}); panel?.close(true); }
162
+ };
163
+ panels.set(id, entry);
164
+ const methods = {
165
+ cancel: () => panel?.close(),
166
+ async save() {
167
+ if (saving.peek()) return;
168
+ saving.value = true;
169
+ try {
170
+ const next = await api.saveChat(id, routingBody(values()));
171
+ ctx.take(next);
172
+ E.toast('Saved.', {type: 'success'});
173
+ panel?.close(true);
174
+ } catch (err) {
175
+ E.toast(`Not saved: ${err.message || err}`, {type: 'error'});
176
+ } finally {
177
+ saving.value = false;
178
+ }
179
+ }
180
+ };
181
+ try {
182
+ panel = await openPanel({title: c.name, size: 'md', html, methods, dirty, busy: () => saving.peek(),
183
+ model: {name, alertsOn, sev, allSources, sourceList: M.observable(sources), formsOn, allForms, formList: M.observable(forms), detail, saving},
184
+ cleanup: () => panels.delete(id)});
185
+ } catch (err) {
186
+ panels.delete(id);
187
+ E.toast(`Not opened: ${err.message || err}`, {type: 'error'});
188
+ }
189
+ }
190
+
191
+ const bindings = M.applyBindings({rows, link, connected, botAt, making}, view, {
192
+ methods: {
193
+ async code() {
194
+ making.value = true;
195
+ await run(() => api.linkCode());
196
+ making.value = false;
197
+ },
198
+ copyCode: () => copy(link.peek().line, 'Copied'),
199
+ async check() {
200
+ const before = (s().chats || []).length;
201
+ const next = await run(() => ctx.reload());
202
+ if (!next) return;
203
+ if ((next.chats || []).length > before) E.toast('Linked.', {type: 'success'});
204
+ else E.toast(next.linkCode ? 'Not linked yet - send the /link line in the chat first.' : 'The code was used or has run out - make a new one.', {type: 'warning'});
205
+ }
206
+ }
207
+ });
208
+ wireRows(list, {
209
+ scope, openMenuAt: kit.openMenuAt, main: edit,
210
+ items: (id) => {
211
+ const c = chat(id);
212
+ if (!c) return [];
213
+ return manage ? [
214
+ {label: 'What it gets…', icon: 'sliders', action: () => edit(id)},
215
+ {label: 'Send a test', icon: 'send', action: () => test(id)},
216
+ {label: c.paused ? 'Resume' : 'Pause', icon: c.paused ? 'play' : 'pause', action: () => pause(id)},
217
+ {type: 'divider'},
218
+ {label: 'Unlink…', icon: 'x', action: () => unlink(id)}
219
+ ] : [{label: 'Only an administrator can change chats', disabled: true}];
220
+ }
221
+ });
222
+ return () => { bindings.dispose(); stop(); };
223
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Telegram › Connection - the site's own bot, made with @BotFather. The token is typed here once, checked
3
+ * with Telegram, and kept on the server; it is never sent back, and never kept as a draft.
4
+ */
5
+ import {api, esc} from '../lib/kit.js';
6
+ import {connectionView} from '../lib/arrange.js';
7
+
8
+ export async function mount(root, ctx) {
9
+ const {kit, scope, here, status} = ctx;
10
+ const v = M.observable(connectionView(status.peek()));
11
+ const stop = M.effect(() => { v.value = connectionView(status.value); });
12
+ const token = M.observable('');
13
+ const connecting = M.observable(false);
14
+
15
+ root.innerHTML = `<div class="tg-stack">
16
+ <section class="tg-card">
17
+ <header><h3><span data-icon="send" data-icon-size="16"></span> Your bot <span data-help-title="Your own Telegram bot" data-help="The site talks to Telegram through a bot you make yourself with @BotFather, Telegram's own bot for making bots. It is free. The bot sends the team the site's alerts and form submissions, in the chats you link under Chats. Use a bot for this site alone: one bot can only deliver its messages to one place, so a bot already used by Takeaway or another site is refused."></span></h3>
18
+ <span class="tg-chip is-ok" data-bind-hidden="!v.value.connected" data-bind-text="v.value.botAt"></span>
19
+ <span class="tg-chip" data-bind-hidden="v.value.connected">Not connected</span></header>
20
+
21
+ <div class="tg-stack" data-bind-hidden="!v.value.connected">
22
+ <p class="tg-note is-bad" data-bind-hidden="!v.value.hookError" data-bind-text="v.value.hookError"></p>
23
+ <p class="tg-note">Connected as <a target="_blank" rel="noopener" data-bind-href="v.value.botLink" data-bind-text="v.value.botAt"></a>, sending to this site at <b data-bind-text="v.value.base"></b>. <span data-bind-text="v.value.chats"></span>.
24
+ <span data-help="Telegram delivers what people send the bot to this address (its webhook), with a secret only this site knows. If the site moves to a new address, connect the bot again so Telegram follows."></span></p>
25
+ <p class="tg-note" data-bind-hidden="!v.value.pending" data-bind-text="v.value.pending"></p>
26
+ <div class="tg-bar" data-bind-hidden="!v.value.manage">
27
+ <a class="btn btn-sm btn-primary" href="#/plugins/telegram/chats"><span data-icon="users" data-icon-size="13"></span> Link a chat</a>
28
+ <span class="tg-spacer"></span>
29
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="disconnect">Disconnect the bot</button>
30
+ <span data-help="Disconnecting tells Telegram to stop sending to this site and forgets the token and every linked chat here. The bot itself stays in your Telegram account; delete it with @BotFather if you no longer want it."></span>
31
+ </div>
32
+ </div>
33
+
34
+ <div class="tg-stack" data-bind-hidden="v.value.connected">
35
+ <ol class="tg-steps">
36
+ <li>In Telegram, open <a href="https://t.me/BotFather" target="_blank" rel="noopener">@BotFather</a> and send <code class="tg-code">/newbot</code>.</li>
37
+ <li>Give it a name (like "Acme Alerts") and a username ending in "bot" (like acme_alerts_bot).</li>
38
+ <li>Paste the token it gives you here and click Connect.</li>
39
+ </ol>
40
+ <div class="tg-token" data-bind-hidden="!v.value.manage">
41
+ <input class="form-input" type="password" placeholder="123456789:AAE…" autocomplete="off" aria-label="Bot token" data-model="token.value">
42
+ <button type="button" class="btn btn-sm btn-primary" data-bind-disabled="connecting.value || !token.value" data-on-click="connect" data-bind-text="connecting.value ? 'Connecting…' : 'Connect'"></button>
43
+ <span data-help-title="The bot token" data-help="The long line @BotFather gives you, like 123456789:AAE… It is a password for the bot: anyone with it can send as the bot. It stays on this server and is never shown again, not even to you. If it leaks, send /revoke to @BotFather and connect the new one."></span>
44
+ </div>
45
+ <p class="tg-note" data-bind-hidden="v.value.manage">Ask an administrator to connect the site's bot.</p>
46
+ <p class="tg-note">Telegram can only reach a site on https. The token stays on this server.</p>
47
+ </div>
48
+ </section>
49
+
50
+ <section class="tg-card">
51
+ <header><h3><span data-icon="shield" data-icon-size="16"></span> What is sent to Telegram <span data-help="Telegram keeps messages on its own servers; bot chats are not end-to-end encrypted. Send only what your team may read there."></span></h3></header>
52
+ <ul class="tg-steps">
53
+ <li><b>Alerts</b>: the notification's title, its text, how serious it is, the Tool that raised it and a link to the admin. Notifications meant for one named person (a to-do reminder, say) are never sent.</li>
54
+ <li><b>Form submissions</b>: the form's title and a link to its submissions, and - unless a chat is set to "title and link only" - each answer with its question. Passwords, files, images and hidden fields are never sent.</li>
55
+ <li><b>Nothing else</b> leaves the site, and nothing is sent to a chat that has not been linked with a code from this screen.</li>
56
+ </ul>
57
+ </section></div>`;
58
+ const view = root.firstElementChild;
59
+ scope(kit.helpPopovers(view, {position: 'bottom'}));
60
+ I.scan(view);
61
+
62
+ const bindings = M.applyBindings({v, token, connecting}, view, {
63
+ methods: {
64
+ async connect() {
65
+ if (connecting.peek()) return;
66
+ connecting.value = true;
67
+ try {
68
+ // Refused: the token stays in its box, so a typo is fixed rather than pasted again.
69
+ const next = await api.connect(token.peek().trim(), location.origin);
70
+ if (!here()) return;
71
+ token.value = '';
72
+ ctx.take(next);
73
+ E.toast(`Connected as @${next.botName}.`, {type: 'success'});
74
+ } catch (err) {
75
+ E.toast(err.message || String(err), {type: 'error'});
76
+ } finally {
77
+ connecting.value = false;
78
+ }
79
+ },
80
+ async disconnect() {
81
+ const n = (status.peek()?.chats || []).length;
82
+ const ok = await E.confirm(`Disconnect ${esc(v.peek().botAt)}? Telegram stops sending to this site${n ? ` and the ${n} linked chat${n === 1 ? '' : 's'} stop getting messages` : ''}.`,
83
+ {title: 'Disconnect the bot', confirmText: 'Disconnect', cancelText: 'Keep it'});
84
+ if (!ok || !here()) return;
85
+ try { ctx.take(await api.disconnect()); E.toast('Disconnected.', {type: 'success'}); } catch (err) { E.toast(err.message || String(err), {type: 'error'}); }
86
+ }
87
+ }
88
+ });
89
+ return () => { bindings.dispose(); stop(); };
90
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Telegram - one Tool, its screens as tabs under the banner:
3
+ *
4
+ * #/plugins/telegram Connection (the bot)
5
+ * #/plugins/telegram/chats Chats (linked chats and what each gets)
6
+ * #/plugins/telegram/test Test (send a sample, or raise a real notification)
7
+ *
8
+ * Path segments, not ?query: the admin router 404s a query on a fresh load. One GET /status feeds every tab;
9
+ * each tab is its own module with mount(root, ctx) -> cleanup, all on domma-reactive bindings.
10
+ */
11
+ import {api, loadKit} from '../lib/kit.js';
12
+
13
+ const ROUTE = /^#\/plugins\/telegram(\/|$)/;
14
+ const TABS = [
15
+ {key: 'connection', label: 'Connection', icon: 'link', module: '/plugins/telegram/admin/views/connection.js'},
16
+ {key: 'chats', label: 'Chats', icon: 'users', module: '/plugins/telegram/admin/views/chats.js'},
17
+ {key: 'test', label: 'Test', icon: 'send', module: '/plugins/telegram/admin/views/test.js', manage: true}
18
+ ];
19
+
20
+ let lifetime = null;
21
+
22
+ const tabFromHash = () => (location.hash.match(/^#\/plugins\/telegram\/([a-z-]+)/)?.[1] || 'connection');
23
+
24
+ export const telegramView = {
25
+ templateUrl: '/plugins/telegram/admin/templates/telegram.html',
26
+
27
+ async onMount($container) {
28
+ const kit = await loadKit();
29
+ lifetime ??= kit.viewLifetime(ROUTE);
30
+ if (!ROUTE.test(location.hash)) return;
31
+ lifetime.reset();
32
+ const scope = (fn) => { lifetime.add(fn); return fn; };
33
+ const container = $container.get(0);
34
+ const root = container.querySelector('[data-tg-admin]') || container;
35
+ const mountedFor = location.hash;
36
+ const here = () => location.hash === mountedFor && root.isConnected;
37
+
38
+ const status = M.observable(null);
39
+ const error = M.observable('');
40
+ const tabs = M.observable([]);
41
+ root.innerHTML = `
42
+ <div class="tg-loading" data-bind-hidden="status.value || error.value">Loading…</div>
43
+ <p class="tg-note is-bad" hidden data-bind-hidden="!error.value" data-bind-text="error.value"></p>
44
+ <nav class="tg-nav" aria-label="Telegram" hidden data-bind-hidden="!status.value" data-each="tabs.value key=key"><a data-bind-href="href" data-bind-class="on ? 'is-on' : ''" data-bind-aria-current="on ? 'page' : false"><span data-bind-text="label"></span></a></nav>
45
+ <div class="tg-body"></div>`;
46
+ const body = root.querySelector('.tg-body');
47
+ const bindings = M.applyBindings({status, error, tabs}, root);
48
+ scope(() => bindings.dispose());
49
+
50
+ let first;
51
+ try {
52
+ first = await api.status();
53
+ } catch (err) {
54
+ if (here()) error.value = `Telegram could not load: ${err.message || err}`;
55
+ return;
56
+ }
57
+ if (!here()) return;
58
+ const shown = TABS.filter(t => !t.manage || first.can?.manage);
59
+ const current = shown.find(t => t.key === tabFromHash()) || shown[0];
60
+ tabs.value = shown.map(t => ({key: t.key, label: t.label, href: t.key === 'connection' ? '#/plugins/telegram' : `#/plugins/telegram/${t.key}`, on: t === current}));
61
+ status.value = first;
62
+
63
+ const ctx = {
64
+ kit, scope, here, container, $container,
65
+ status,
66
+ /** Fetch the status again (after a change) - every tab reads the same observable. */
67
+ async reload() {
68
+ const next = await api.status();
69
+ if (here()) status.value = next;
70
+ kit.sidebarCount('#/plugins/telegram');
71
+ return next;
72
+ },
73
+ /** Take a route's answer (every write answers with the status). */
74
+ take(next) {
75
+ if (next && here()) status.value = next;
76
+ kit.sidebarCount('#/plugins/telegram');
77
+ },
78
+ go(tab) { location.hash = tab === 'connection' ? '#/plugins/telegram' : `#/plugins/telegram/${tab}`; }
79
+ };
80
+ try {
81
+ const mod = await import(current.module);
82
+ if (!here()) return;
83
+ const cleanup = await mod.mount(body, ctx);
84
+ if (typeof cleanup === 'function') scope(cleanup);
85
+ } catch (err) {
86
+ if (here()) error.value = `This screen could not load: ${err.message || err}`;
87
+ }
88
+ }
89
+ };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Telegram › Test - try a chat before relying on it: a hello, a sample alert, a sample form entry (as that
3
+ * chat would get it), or a real notification raised in the bell, which then travels the whole way (the
4
+ * notification, each chat's routing, the queue) like any other.
5
+ */
6
+ import {api} from '../lib/kit.js';
7
+
8
+ const KINDS = [
9
+ {id: 'hello', label: 'A hello', help: 'A short message naming the chat. Proves the bot can post there.'},
10
+ {id: 'alert', label: 'A sample alert', help: 'What a warning looks like in this chat. Sent whatever the chat\'s alert choices are.'},
11
+ {id: 'form', label: 'A sample form entry', help: 'What a submission of the chosen form looks like in this chat, with placeholders for the answers - or the title and link only, if the chat is set to that.'},
12
+ {id: 'notification', label: 'A real notification', help: 'Raises a test notification in the admin\'s bell (from "Telegram test alerts"). Every chat whose routing takes that severity gets it - the whole path, as a real alert would travel.'}
13
+ ];
14
+
15
+ export async function mount(root, ctx) {
16
+ const {kit, scope, here, status} = ctx;
17
+ const chats = M.observable([]);
18
+ const forms = M.observable([]);
19
+ const connected = M.observable(false);
20
+ const chat = M.observable('');
21
+ const kind = M.observable('hello');
22
+ const form = M.observable('');
23
+ const severity = M.observable('warning');
24
+ const sending = M.observable(false);
25
+ const result = M.observable('');
26
+ const stop = M.effect(() => {
27
+ const st = status.value || {};
28
+ connected.value = Boolean(st.connected);
29
+ chats.value = (st.chats || []).map(c => ({id: c.id, name: c.paused ? `${c.name} (paused)` : c.name}));
30
+ forms.value = (st.forms || []).map(f => ({id: f.slug, name: f.title}));
31
+ if (!chats.peek().some(c => c.id === chat.peek())) chat.value = chats.peek()[0]?.id || '';
32
+ if (!forms.peek().some(f => f.id === form.peek())) form.value = forms.peek()[0]?.id || '';
33
+ });
34
+
35
+ root.innerHTML = `<div class="tg-stack">
36
+ <p class="tg-note is-warn" data-bind-hidden="connected.value">Connect the bot first, on the <a href="#/plugins/telegram">Connection</a> tab.</p>
37
+ <section class="tg-card" data-bind-hidden="!connected.value">
38
+ <header><h3><span data-icon="send" data-icon-size="16"></span> Send a test <span data-help-title="Testing" data-help="Send something to a linked chat to see it arrive, and how it looks. Nothing here changes a chat's settings."></span></h3></header>
39
+ <div class="tg-test">
40
+ <label class="form-label" for="tg-test-kind">What to send</label>
41
+ <div class="tg-stack">${KINDS.map(k => `<label class="tg-check"><input type="radio" name="tg-test-kind" value="${k.id}" data-model="kind.value"> ${k.label} <span data-help="${k.help}"></span></label>`).join('')}</div>
42
+
43
+ <label class="form-label" for="tg-test-chat" data-bind-hidden="kind.value === 'notification'">To</label>
44
+ <select id="tg-test-chat" class="form-select" data-bind-hidden="kind.value === 'notification'" data-model="chat.value" data-each="chats.value key=id"><option data-bind-value="id">{{name}}</option></select>
45
+
46
+ <label class="form-label" for="tg-test-form" data-bind-hidden="kind.value !== 'form'">Form</label>
47
+ <select id="tg-test-form" class="form-select" data-bind-hidden="kind.value !== 'form'" data-model="form.value" data-each="forms.value key=id"><option data-bind-value="id">{{name}}</option></select>
48
+
49
+ <label class="form-label" for="tg-test-sev" data-bind-hidden="kind.value !== 'notification'">How serious</label>
50
+ <select id="tg-test-sev" class="form-select" data-bind-hidden="kind.value !== 'notification'" data-model="severity.value">
51
+ <option value="info">Info</option><option value="success">Success</option><option value="warning">Warning</option><option value="critical">Critical</option></select>
52
+ </div>
53
+ <p class="tg-note" data-bind-hidden="kind.value === 'notification' || chats.value.length">No chats are linked yet - link one under <a href="#/plugins/telegram/chats">Chats</a>.</p>
54
+ <div class="tg-bar"><button type="button" class="btn btn-sm btn-primary" data-on-click="send" data-bind-disabled="sending.value || (kind.value !== 'notification' && !chat.value) || (kind.value === 'form' && !form.value)" data-bind-text="sending.value ? 'Sending…' : 'Send'"></button>
55
+ <span class="tg-note" data-bind-text="result.value"></span></div>
56
+ </section></div>`;
57
+ const view = root.firstElementChild;
58
+ scope(kit.helpPopovers(view, {position: 'bottom'}));
59
+ I.scan(view);
60
+
61
+ const bindings = M.applyBindings({chats, forms, connected, chat, kind, form, severity, sending, result}, view, {
62
+ methods: {
63
+ async send() {
64
+ if (sending.peek()) return;
65
+ sending.value = true;
66
+ result.value = '';
67
+ try {
68
+ const k = kind.peek();
69
+ const r = await api.test(k === 'notification' ? {kind: k, severity: severity.peek()} : {kind: k, chat: chat.peek(), form: form.peek()});
70
+ if (!here()) return;
71
+ result.value = r.note || 'Sent - look in that chat.';
72
+ E.toast(k === 'notification' ? 'Raised.' : 'Sent.', {type: 'success'});
73
+ kit.sidebarCount('#/plugins/telegram');
74
+ } catch (err) {
75
+ if (here()) result.value = '';
76
+ E.toast(err.message || String(err), {type: 'error'});
77
+ } finally {
78
+ sending.value = false;
79
+ }
80
+ }
81
+ }
82
+ });
83
+ return () => { bindings.dispose(); stop(); };
84
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Telegram - default settings (config/plugins.json `telegram.settings`). Written only by the Tool's own
3
+ * routes: the token, the webhook secret and the link code never reach a browser.
4
+ *
5
+ * botToken, botName the bot made with @BotFather
6
+ * secret our webhook secret (Telegram's X-Telegram-Bot-Api-Secret-Token)
7
+ * base the site's https address, given when the bot was connected
8
+ * linkSecret, linkSecretUntil the one-time "/link" code
9
+ * chats linked chats with their routing (lib/messages.js)
10
+ */
11
+ export default {
12
+ botToken: '',
13
+ botName: '',
14
+ secret: '',
15
+ base: '',
16
+ linkSecret: '',
17
+ linkSecretUntil: '',
18
+ linkOwnerId: '',
19
+ linkOwnerName: '',
20
+ chats: []
21
+ };
@@ -0,0 +1,87 @@
1
+ ---
2
+ title: Guide
3
+ order: 1
4
+ ---
5
+
6
+ Telegram sends your team the site's alerts and form submissions, through a Telegram bot of your own. It is free, and so is Telegram.
7
+
8
+ ## What it does
9
+
10
+ - Sends the notifications the site raises (a payment failed, the disk is filling, a Tool stopped) to a Telegram chat, as they happen.
11
+ - Sends each form submission to a chat, with the answers or just the form's title and a link.
12
+ - Works with any number of chats: your team's group, or one person's private chat with the bot. Each chat chooses what it gets.
13
+
14
+ Telegram Pro (paid) adds two-way chat with your customers. See its own guide.
15
+
16
+ ## Getting started
17
+
18
+ 1. In Telegram, open **@BotFather** and send `/newbot`. Give the bot a name (like "Acme Alerts") and a username ending in "bot".
19
+ 2. BotFather answers with a token, a long line like `123456789:AAE…`. Copy it.
20
+ 3. Open [Telegram](#/plugins/telegram) from the admin sidebar, paste the token on the **Connection** tab and click **Connect**.
21
+ 4. On the **Chats** tab, click **Link a chat**. A one-time code appears.
22
+ 5. In Telegram, add the bot to your team's group (or open a private chat with it) and send the line shown, `/link` and the code.
23
+ 6. Click **Check**. The chat appears in the list, getting warning and critical alerts.
24
+ 7. Click the chat to choose what else it gets.
25
+
26
+ Use a bot for this site alone. One bot can deliver its messages to one place only, so the Tool refuses a bot that Takeaway or another site already uses: make a second bot for it.
27
+
28
+ The site must be on https: Telegram does not deliver to plain http.
29
+
30
+ ## Screens
31
+
32
+ ### Connection
33
+
34
+ Shows the bot and where Telegram delivers to. **Disconnect the bot** tells Telegram to stop and forgets the token and every linked chat. A red note means Telegram reports it cannot reach the site; connect the bot again to repair it.
35
+
36
+ ### Chats
37
+
38
+ Every linked chat, with what it gets. Click a chat (or press Enter) to change it; right-click, the ⋮ button or Shift+F10 opens the menu:
39
+
40
+ | Menu item | What it does |
41
+ |---|---|
42
+ | What it gets… | Opens the chat's settings |
43
+ | Send a test | Sends a short hello to that chat |
44
+ | Pause / Resume | Stops everything going to the chat until you resume it |
45
+ | Unlink… | Stops the chat getting anything and tells the chat so |
46
+
47
+ In a chat's settings:
48
+
49
+ - **Name in this admin**: only for you; Telegram does not see it.
50
+ - Saving makes you the chat's owner: from then on it gets only alerts you would see in the bell and forms whose submissions you may read.
51
+ - **Alerts**: how serious an alert must be (Info, Success, Warning, Critical) and from which Tools. A new chat gets Warning and Critical from every Tool.
52
+ - **Form submissions**: which forms (or every form, including new ones), and what the message holds:
53
+ - **The form's title, the answers and a link** (the default once forms are switched on), or
54
+ - **The form's title and a link only**: nothing the visitor typed leaves the site.
55
+
56
+ Closing the settings with changes asks first. Leaving the screen keeps the changes in this browser and offers them back next time.
57
+
58
+ ### Test
59
+
60
+ Sends a hello, a sample alert or a sample form entry to a chosen chat, or raises **a real notification** in the bell, which then travels to every chat whose settings take it, like any other alert.
61
+
62
+ ## What is sent to Telegram
63
+
64
+ Telegram keeps messages on its own servers, and chats with bots are not end-to-end encrypted. Send only what your team may read there.
65
+
66
+ | Message | What it holds | Who gets it |
67
+ |---|---|---|
68
+ | Alert | The notification's title and text, how serious it is, the Tool that raised it, the site's name, a link to the admin | Every linked chat whose settings take that severity and Tool |
69
+ | Form submission | The form's title, the site's name, a link to the form's submissions, and (unless set to title and link only) each question with its answer | Every linked chat that has that form switched on |
70
+ | Link and test messages | Confirmations such as "Linked as Office", the test message you chose | The chat concerned |
71
+
72
+ Never sent:
73
+
74
+ - notifications meant for one named person, such as a to-do reminder;
75
+ - passwords, uploaded files, images and hidden fields from a form, or any answer whose question is not on the form;
76
+ - anything to a chat that has not been linked with a code from the Chats tab;
77
+ - anything the chat's owner could not see themselves. The owner is whoever made the chat's link code, then whoever last changed what it gets (shown on the chat). An alert goes to a chat only if its owner would see it in the bell (a notification for Super Admins only never reaches a chat an admin set up), and a form only if its owner may read that form's submissions. If the owner's account is removed or switched off, the chat stops getting messages until someone else saves its settings.
78
+
79
+ Notifications pushed by Domma's own server and the sample notifications from the Notifications settings are not sent to Telegram.
80
+
81
+ ## Good to know
82
+
83
+ - Messages to one chat go out about one a second, as Telegram asks. A burst waits its turn; after 50 waiting, more are dropped (the bell still has them).
84
+ - A message that cannot be sent never stops the form or the notification. The chat shows the reason in red, and the sidebar badge turns red.
85
+ - The link code works once, for 15 minutes. A chat that sends five wrong codes is ignored until you make a new one.
86
+ - In a linked chat, `/unlink` stops it getting anything.
87
+ - If a Telegram group becomes a "supergroup" (Telegram does this as groups grow), it stays linked.