@scalio-cloud/ui 0.28.0 → 0.29.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.
package/README.md CHANGED
@@ -325,6 +325,30 @@ const reset = factoryResetApi(api); // once, outside the component
325
325
  `SettingsField` (label, field, help) and `SettingsRow` (title and help left, a switch or button right; `tone="danger"`)
326
326
  keep the fields inside a `SettingsSection` the same in every app.
327
327
 
328
+ ## Benachrichtigungen: E-Mail-Versand und E-Mail-Vorlagen (React)
329
+
330
+ Since 0.29.0 (ADR 0069 W5) every app sends mail the same way. The server side is scalio-platform 0.8.0 `mail`
331
+ (`Mailer.router`, mounted at `/api/mail`). Both blocks go into the settings group «Benachrichtigungen».
332
+
333
+ ```jsx
334
+ import { MailTransport, MailTemplates, mailApi } from "@scalio-cloud/ui/react";
335
+ import { RichTextEditor } from "@/components/RichTextEditor"; // optional, the app's own editor (Compass: react-quill-new)
336
+
337
+ const mail = mailApi(api); // once, outside the component; mailApi(api, "/admin/mail") for another prefix
338
+ <MailTransport client={mail} lang={lang} notify={toast} graphHint={t("...Mail.Send and Mail.ReadWrite...")}>
339
+ <InboxSettings /> {/* optional blocks after «Testmail» */}
340
+ </MailTransport>
341
+ <MailTemplates client={mail} lang={lang} editor={RichTextEditor} />
342
+ ```
343
+
344
+ `MailTransport` shows three blocks: «E-Mail-Versand» (off, SMTP or Microsoft 365, sender, language; secrets come back
345
+ as a mask and the mask is sent back unchanged), «Testmail» (empty recipient: to me) and «Letzte Mails» (`outbox={false}`
346
+ hides it). On a test instance the backend answers `test_mailbox: true` and the server fields are locked.
347
+ `MailTemplates` picks mail and language, offers the placeholders as buttons, shows the preview of the real rendering
348
+ in a sandboxed frame, and saves, tests («Test an mich») or resets to the built-in text. A switchable mail gets the
349
+ checkbox «Diese Mail senden». The `editor` gets `{value, onChange, testId}`; without it a text field is used, so this
350
+ package keeps no dependencies. With an editor, plain built-in texts are passed as paragraphs (`textToHtml`).
351
+
328
352
  ## Protokoll: Aktionen und Jobs (React)
329
353
 
330
354
  One menu item «Protokoll» with two tabs like Nexus (scalio-docs ADR 0070). The server side is scalio-platform
package/nav.css CHANGED
@@ -745,3 +745,35 @@
745
745
  .scalio-jobs-card-foot { margin-top: auto; display: flex; align-items: center; justify-content: flex-end; gap: 0.5rem; }
746
746
  .scalio-jobs-steps { margin: 0; padding-left: 1.25rem; display: flex; flex-direction: column; gap: 0.375rem; }
747
747
  .scalio-jobs-steps li { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
748
+
749
+ /* E-Mail-Versand and E-Mail-Vorlagen (ADR 0069 W5, react/mail.js) */
750
+ .scalio-mail-providers { display: flex; flex-wrap: wrap; gap: 0.5rem 1.25rem; margin: 0; padding: 0; border: 0; }
751
+ .scalio-mail-providers legend { width: 100%; margin-bottom: 0.5rem; }
752
+ .scalio-mail-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: 1rem; }
753
+ .scalio-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
754
+ .scalio-mail-test { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem; }
755
+ .scalio-mail-test .scalio-input { flex: 1 1 15rem; width: auto; }
756
+ .scalio-mail-outbox { overflow-x: auto; }
757
+ .scalio-mail-outbox table { width: 100%; border-collapse: collapse; font-size: 0.875rem; }
758
+ .scalio-mail-outbox td { padding: 0.5rem 0.75rem 0.5rem 0; border-bottom: 1px solid hsl(var(--border)); vertical-align: top; }
759
+ .scalio-mail-outbox tr:last-child td { border-bottom: 0; }
760
+ .scalio-mail-time { white-space: nowrap; font-size: 0.75rem; color: hsl(var(--muted-foreground)); }
761
+ .scalio-mail-state { text-align: right; padding-right: 0 !important; }
762
+ .scalio-settings-help.is-error { color: hsl(var(--destructive)); }
763
+ .scalio-mail-tokens { display: flex; flex-wrap: wrap; gap: 0.375rem; margin-top: 0.375rem; }
764
+ .scalio-mail-token {
765
+ padding: 0.125rem 0.5rem; border: 1px solid hsl(var(--primary) / 0.25); border-radius: 2px; background: hsl(var(--primary) / 0.06);
766
+ color: hsl(var(--primary)); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.75rem; cursor: pointer;
767
+ }
768
+ .scalio-mail-token:hover { background: hsl(var(--primary) / 0.12); }
769
+ .scalio-mail-editor-head { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; margin-bottom: -0.5rem; }
770
+ .scalio-mail-editor { display: grid; grid-template-columns: 1fr; gap: 1rem; }
771
+ .scalio-mail-editor.has-preview { grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr)); }
772
+ .scalio-mail-editor-pane { min-width: 0; }
773
+ .scalio-mail-body { width: 100%; min-height: 20rem; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.8125rem; }
774
+ .scalio-mail-preview { display: flex; flex-direction: column; min-height: 20rem; border: 1px solid hsl(var(--border)); border-radius: 2px; overflow: hidden; }
775
+ .scalio-mail-preview-head { display: flex; justify-content: space-between; padding: 0.5rem 0.75rem; border-bottom: 1px solid hsl(var(--border)); font-size: 0.75rem; color: hsl(var(--muted-foreground)); }
776
+ .scalio-mail-preview-head strong { text-transform: uppercase; letter-spacing: 0.05em; }
777
+ .scalio-mail-preview-subject { padding: 0.5rem 0.75rem; border-bottom: 1px solid hsl(var(--border)); font-size: 0.875rem; }
778
+ .scalio-mail-preview-subject span { font-weight: 600; }
779
+ .scalio-mail-preview iframe { flex: 1; width: 100%; min-height: 16rem; border: 0; background: #fff; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalio-cloud/ui",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "description": "Scalio Control Room design tokens, Tailwind preset, self-hosted fonts, the shared app header, sign-in layout, sidebar and page blocks",
5
5
  "license": "SEE LICENSE IN README.md",
6
6
  "private": false,
@@ -67,8 +67,8 @@
67
67
  "node": ">=18"
68
68
  },
69
69
  "devDependencies": {
70
- "jsdom": "25.0.1",
71
- "react": "19.1.0",
72
- "react-dom": "19.1.0"
70
+ "jsdom": "30.1.3",
71
+ "react": "19.3.1",
72
+ "react-dom": "19.3.1"
73
73
  }
74
74
  }
package/react/index.js CHANGED
@@ -378,6 +378,6 @@ module.exports = {
378
378
  TEST_IDS,
379
379
  initials,
380
380
  };
381
- Object.assign(module.exports, Nav, Blocks, require("./settings"), require("./support"), require("./beacon"), require("./security"), require("./license"), require("./palette"), require("./unify"), require("./profile"), require("./actions"), require("./selftest"), require("./users"), require("./roles"), require("./wizard"), require("./maintenance"), require("./audit"));
381
+ Object.assign(module.exports, Nav, Blocks, require("./settings"), require("./support"), require("./beacon"), require("./security"), require("./license"), require("./palette"), require("./unify"), require("./profile"), require("./actions"), require("./selftest"), require("./users"), require("./roles"), require("./wizard"), require("./maintenance"), require("./audit"), require("./mail"));
382
382
  // After the exports above: auth.js uses LanguageToggle and ThemeToggle from this module.
383
383
  Object.assign(module.exports, require("./auth"));
package/react/mail.js ADDED
@@ -0,0 +1,473 @@
1
+ "use strict";
2
+ // Einstellungen -> Benachrichtigungen (ADR 0069 wartung/W5, Welle 2): «E-Mail-Versand» (MailTransport) and
3
+ // «E-Mail-Vorlagen» (MailTemplates), the same in every app. Backend: scalio-platform `mail` (Mailer.router, /api/mail).
4
+ // The rich text editor comes from the app (prop editor, e.g. react-quill-new like Compass); without it a text field.
5
+ const React = require("react");
6
+ const h = React.createElement;
7
+ const Icons = require("./icons");
8
+ const { SettingsSection, SettingsField: Field } = require("./settings");
9
+
10
+ const LABELS = {
11
+ de: {
12
+ transportTitle: "E-Mail-Versand",
13
+ transportHint: "Über welchen Server die App Mails schickt. Passwort und Client-Secret werden verschlüsselt gespeichert und nie angezeigt.",
14
+ provider: "Mails senden mit",
15
+ providers: { off: "Aus", smtp: "SMTP-Server", graph: "Microsoft 365" },
16
+ fromName: "Absendername",
17
+ fromAddress: "Absenderadresse",
18
+ language: "Sprache der Mails",
19
+ languageHint: "Gilt, wenn die App die Sprache der empfangenden Person nicht kennt.",
20
+ host: "Server",
21
+ port: "Port",
22
+ security: "Verbindungssicherheit",
23
+ securities: { starttls: "STARTTLS", ssl: "SSL/TLS", none: "Keine (nicht empfohlen)" },
24
+ username: "Benutzername",
25
+ password: "Passwort",
26
+ tenantId: "Tenant-ID",
27
+ clientId: "Client-ID der App",
28
+ clientSecret: "Client-Secret",
29
+ sender: "Postfach, das sendet",
30
+ graphHint: "Die App braucht die Anwendungsberechtigung Mail.Send. Beschränken Sie sie in Exchange Online mit «RBAC for Applications» auf das Postfach, das sendet.",
31
+ testMailbox: "Testinstanz: Mails gehen über das Testpostfach, die Einstellungen hier gelten nicht.",
32
+ save: "Speichern",
33
+ saved: "Gespeichert",
34
+ testTitle: "Testmail",
35
+ testHint: "Schickt sofort eine Mail mit den gespeicherten Einstellungen und zeigt den Fehler, wenn es nicht klappt.",
36
+ recipient: "Empfänger (leer: an mich)",
37
+ sendTest: "Testmail senden",
38
+ testSent: "Testmail gesendet an {to}",
39
+ outboxTitle: "Letzte Mails",
40
+ outboxHint: "Wartende Mails werden alle 30 Sekunden gesendet, bei Fehlern bis zu fünfmal.",
41
+ outboxEmpty: "Noch keine Mails.",
42
+ refresh: "Aktualisieren",
43
+ states: { pending: "Wartet", sent: "Gesendet", failed: "Fehlgeschlagen" },
44
+ templatesTitle: "E-Mail-Vorlagen",
45
+ templatesHint: "Betreff und Text jeder Mail pro Sprache. Platzhalter wie {name} werden beim Versand ersetzt. Ohne eigene Vorlage gilt der eingebaute Text.",
46
+ kind: "Mail",
47
+ lang: "Sprache",
48
+ languages: { de: "Deutsch", en: "Englisch" },
49
+ own: "eigene Vorlage",
50
+ builtIn: "Eingebauter Text. Speichern Sie, um ihn anzupassen.",
51
+ custom: "Eigene Vorlage für diese Sprache.",
52
+ enabled: "Diese Mail senden",
53
+ tokens: "Platzhalter (Klick fügt ein)",
54
+ subject: "Betreff",
55
+ body: "Text",
56
+ preview: "Vorschau",
57
+ showPreview: "Vorschau zeigen",
58
+ hidePreview: "Vorschau ausblenden",
59
+ sample: "Beispieldaten",
60
+ saveTemplate: "Vorlage speichern",
61
+ testToMe: "Test an mich",
62
+ resetTemplate: "Auf Standard zurücksetzen",
63
+ templateSaved: "Vorlage gespeichert",
64
+ templateReset: "Eingebauter Text gilt wieder",
65
+ off: "Der Versand ist ausgeschaltet. Vorlagen können Sie trotzdem bearbeiten.",
66
+ },
67
+ en: {
68
+ transportTitle: "E-mail sending",
69
+ transportHint: "Which server the app sends mail through. Password and client secret are stored encrypted and never shown.",
70
+ provider: "Send mail with",
71
+ providers: { off: "Off", smtp: "SMTP server", graph: "Microsoft 365" },
72
+ fromName: "Sender name",
73
+ fromAddress: "Sender address",
74
+ language: "Language of the mails",
75
+ languageHint: "Used when the app does not know the recipient's language.",
76
+ host: "Server",
77
+ port: "Port",
78
+ security: "Connection security",
79
+ securities: { starttls: "STARTTLS", ssl: "SSL/TLS", none: "None (not recommended)" },
80
+ username: "User name",
81
+ password: "Password",
82
+ tenantId: "Tenant ID",
83
+ clientId: "Client ID of the app",
84
+ clientSecret: "Client secret",
85
+ sender: "Mailbox that sends",
86
+ graphHint: "The app needs the application permission Mail.Send. Limit it to the sending mailbox with RBAC for Applications in Exchange Online.",
87
+ testMailbox: "Test instance: mails go through the test mailbox, the settings here do not apply.",
88
+ save: "Save",
89
+ saved: "Saved",
90
+ testTitle: "Test mail",
91
+ testHint: "Sends a mail at once with the saved settings and shows the error if it fails.",
92
+ recipient: "Recipient (empty: to me)",
93
+ sendTest: "Send test mail",
94
+ testSent: "Test mail sent to {to}",
95
+ outboxTitle: "Last mails",
96
+ outboxHint: "Waiting mails are sent every 30 seconds, after an error up to five times.",
97
+ outboxEmpty: "No mails yet.",
98
+ refresh: "Refresh",
99
+ states: { pending: "Waiting", sent: "Sent", failed: "Failed" },
100
+ templatesTitle: "E-mail templates",
101
+ templatesHint: "Subject and text of every mail per language. Placeholders like {name} are filled in when the mail is sent. Without an own template the built-in text applies.",
102
+ kind: "Mail",
103
+ lang: "Language",
104
+ languages: { de: "German", en: "English" },
105
+ own: "own template",
106
+ builtIn: "Built-in text. Save to change it.",
107
+ custom: "Own template for this language.",
108
+ enabled: "Send this mail",
109
+ tokens: "Placeholders (click to insert)",
110
+ subject: "Subject",
111
+ body: "Text",
112
+ preview: "Preview",
113
+ showPreview: "Show preview",
114
+ hidePreview: "Hide preview",
115
+ sample: "Sample data",
116
+ saveTemplate: "Save template",
117
+ testToMe: "Send test to me",
118
+ resetTemplate: "Reset to default",
119
+ templateSaved: "Template saved",
120
+ templateReset: "The built-in text applies again",
121
+ off: "Sending is switched off. You can still edit the templates.",
122
+ },
123
+ };
124
+
125
+ // Plain text (the built-in templates) for a rich text editor: paragraphs and line breaks, HTML escaped.
126
+ function textToHtml(text) {
127
+ if (!text || /<[a-zA-Z/][^>]*>/.test(text)) return text || "";
128
+ const esc = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
129
+ return esc.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean).map((p) => `<p>${p.replace(/\n/g, "<br>")}</p>`).join("");
130
+ }
131
+
132
+ function mailLabels(lang, overrides) {
133
+ return Object.assign({}, LABELS[lang === "en" ? "en" : "de"], overrides || {});
134
+ }
135
+
136
+ function errorText(err) {
137
+ const d = err && err.response && err.response.data && err.response.data.detail;
138
+ if (typeof d === "string") return d;
139
+ if (Array.isArray(d)) return d.map((x) => (x && x.msg) || String(x)).join(" ");
140
+ return (err && err.message) || String(err);
141
+ }
142
+
143
+ function fmtTime(iso, lang) {
144
+ try {
145
+ return new Date(iso).toLocaleString(lang === "en" ? "en-GB" : "de-CH", { dateStyle: "short", timeStyle: "short" });
146
+ } catch (e) {
147
+ return iso || "";
148
+ }
149
+ }
150
+
151
+ // api: axios instance with the app's base URL (/api); base: where the app mounted Mailer.router.
152
+ function mailApi(api, base) {
153
+ const b = base || "/mail";
154
+ const data = (r) => r.data;
155
+ const enc = encodeURIComponent;
156
+ return {
157
+ settings: () => api.get(`${b}/settings`).then(data),
158
+ save: (body) => api.put(`${b}/settings`, body).then(data),
159
+ test: (to) => api.post(`${b}/test`, { to: to || "" }).then(data),
160
+ outbox: () => api.get(`${b}/outbox`).then(data),
161
+ templates: () => api.get(`${b}/templates`).then(data),
162
+ saveTemplate: (kind, lang, body) => api.put(`${b}/templates/${enc(kind)}/${enc(lang)}`, body).then(data),
163
+ resetTemplate: (kind, lang) => api.delete(`${b}/templates/${enc(kind)}/${enc(lang)}`).then(data),
164
+ preview: (body) => api.post(`${b}/templates/preview`, body).then(data),
165
+ testTemplate: (body) => api.post(`${b}/templates/test`, body).then(data),
166
+ };
167
+ }
168
+
169
+ function useMessages(props) {
170
+ const [msg, setMsg] = React.useState(null);
171
+ const fmtErr = props.formatError || errorText;
172
+ return {
173
+ msg,
174
+ ok: (text) => (props.notify ? props.notify(text, "success") : setMsg({ tone: "ok", text })),
175
+ fail: (err) => {
176
+ const text = fmtErr(err);
177
+ if (props.notify) props.notify(text, "error");
178
+ else setMsg({ tone: "error", text });
179
+ },
180
+ clear: () => setMsg(null),
181
+ };
182
+ }
183
+
184
+ function Notice({ msg, testId }) {
185
+ if (!msg) return null;
186
+ return h("div", { className: `scalio-notice is-${msg.tone === "error" ? "error" : "ok"}`, role: msg.tone === "error" ? "alert" : "status", "data-testid": testId }, msg.text);
187
+ }
188
+
189
+ function input(id, value, onChange, extra) {
190
+ return h("input", Object.assign({ id, className: "scalio-input", value: value == null ? "" : value, "data-testid": id,
191
+ onChange: (e) => onChange(e.target.value) }, extra || {}));
192
+ }
193
+
194
+ function select(id, value, options, onChange, extra) {
195
+ return h("select", Object.assign({ id, className: "scalio-input", value, "data-testid": id, onChange: (e) => onChange(e.target.value) }, extra || {}),
196
+ options.map(([v, text]) => h("option", { key: v, value: v }, text)));
197
+ }
198
+
199
+ // Props: client (mailApi), lang, labels, notify(message, tone), formatError(err), graphHint (the app's own text for
200
+ // the Graph permissions, e.g. Beacon also needs Mail.ReadWrite), children (more blocks after «Testmail», e.g. Beacon's
201
+ // mail intake), outbox (false hides «Letzte Mails»).
202
+ function MailTransport(props) {
203
+ const { client, lang } = props;
204
+ const L = mailLabels(lang, props.labels);
205
+ const m = useMessages(props);
206
+ const [form, setForm] = React.useState(null);
207
+ const [busy, setBusy] = React.useState(false);
208
+ const [to, setTo] = React.useState("");
209
+ const [testing, setTesting] = React.useState(false);
210
+ const [testMsg, setTestMsg] = React.useState(null);
211
+ const [rows, setRows] = React.useState([]);
212
+ const showOutbox = props.outbox !== false;
213
+
214
+ const loadOutbox = React.useCallback(() => {
215
+ if (!showOutbox) return Promise.resolve();
216
+ return client.outbox().then((r) => setRows(r || [])).catch(() => setRows([]));
217
+ }, [client, showOutbox]);
218
+ React.useEffect(() => {
219
+ let alive = true;
220
+ client.settings().then((d) => alive && setForm(d)).catch((e) => alive && m.fail(e));
221
+ loadOutbox();
222
+ return () => { alive = false; };
223
+ }, [client]); // eslint-disable-line react-hooks/exhaustive-deps
224
+
225
+ if (!form) return h(SettingsSection, { id: "mail", title: L.transportTitle, description: L.transportHint, testId: "mail-transport" }, h(Notice, { msg: m.msg, testId: "mail-message" }));
226
+
227
+ const set = (patch) => setForm(Object.assign({}, form, patch));
228
+ const part = (name, key) => (v) => set({ [name]: Object.assign({}, form[name], { [key]: v }) });
229
+ const locked = !!form.test_mailbox;
230
+
231
+ const save = async (e) => {
232
+ e.preventDefault();
233
+ setBusy(true);
234
+ m.clear();
235
+ try {
236
+ const body = { provider: form.provider, from_name: form.from_name, from_address: form.from_address, language: form.language };
237
+ if (form.provider === "smtp") body.smtp = Object.assign({}, form.smtp, { port: Number(form.smtp.port) || 587 });
238
+ if (form.provider === "graph") body.graph = form.graph;
239
+ setForm(await client.save(body));
240
+ m.ok(L.saved);
241
+ } catch (err) {
242
+ m.fail(err);
243
+ }
244
+ setBusy(false);
245
+ };
246
+ const test = async () => {
247
+ setTesting(true);
248
+ setTestMsg(null);
249
+ try {
250
+ const r = await client.test(to.trim());
251
+ const text = L.testSent.replace("{to}", (r && r.to) || to);
252
+ if (props.notify) props.notify(text, "success");
253
+ else setTestMsg({ tone: "ok", text });
254
+ loadOutbox();
255
+ } catch (err) {
256
+ const text = (props.formatError || errorText)(err);
257
+ if (props.notify) props.notify(text, "error");
258
+ else setTestMsg({ tone: "error", text });
259
+ }
260
+ setTesting(false);
261
+ };
262
+
263
+ const providers = ["off", "smtp", "graph"];
264
+ const transport = h(
265
+ SettingsSection,
266
+ { id: "mail", title: L.transportTitle, description: L.transportHint, testId: "mail-transport" },
267
+ h(
268
+ "form",
269
+ { className: "scalio-settings-form", onSubmit: save },
270
+ locked ? h("div", { className: "scalio-notice is-info", "data-testid": "mail-test-mailbox" }, L.testMailbox) : null,
271
+ h("fieldset", { className: "scalio-mail-providers", disabled: busy || locked },
272
+ h("legend", { className: "scalio-field-label" }, L.provider),
273
+ providers.map((id) => h("label", { key: id, className: "scalio-settings-check" },
274
+ h("input", { type: "radio", name: "mail-provider", checked: form.provider === id, "data-testid": `mail-provider-${id}`,
275
+ onChange: () => set({ provider: id }) }), h("span", null, L.providers[id])))),
276
+ form.provider !== "off"
277
+ ? h("div", { className: "scalio-mail-grid" },
278
+ h(Field, { id: "mail-from-name", label: L.fromName }, input("mail-from-name", form.from_name, (v) => set({ from_name: v }), { maxLength: 80, disabled: busy })),
279
+ form.provider === "smtp"
280
+ ? h(Field, { id: "mail-from", label: L.fromAddress }, input("mail-from", form.from_address, (v) => set({ from_address: v }),
281
+ { type: "email", maxLength: 254, placeholder: "noreply@example.com", disabled: busy || locked }))
282
+ : null,
283
+ h(Field, { id: "mail-lang", label: L.language, hint: L.languageHint },
284
+ select("mail-lang", form.language, [["de", L.languages.de], ["en", L.languages.en]], (v) => set({ language: v }), { disabled: busy })))
285
+ : null,
286
+ form.provider === "smtp"
287
+ ? h("div", { className: "scalio-mail-grid", "data-testid": "mail-smtp" },
288
+ h(Field, { id: "mail-smtp-host", label: L.host }, input("mail-smtp-host", form.smtp.host, part("smtp", "host"), { maxLength: 253, placeholder: "smtp.example.com", disabled: busy || locked })),
289
+ h(Field, { id: "mail-smtp-port", label: L.port }, input("mail-smtp-port", form.smtp.port, part("smtp", "port"), { type: "number", min: 1, max: 65535, disabled: busy || locked })),
290
+ h(Field, { id: "mail-smtp-security", label: L.security },
291
+ select("mail-smtp-security", form.smtp.security, Object.keys(L.securities).map((k) => [k, L.securities[k]]), part("smtp", "security"), { disabled: busy || locked })),
292
+ h(Field, { id: "mail-smtp-user", label: L.username }, input("mail-smtp-user", form.smtp.username, part("smtp", "username"), { maxLength: 200, autoComplete: "off", disabled: busy || locked })),
293
+ h(Field, { id: "mail-smtp-password", label: L.password }, input("mail-smtp-password", form.smtp.password, part("smtp", "password"),
294
+ { type: "password", maxLength: 500, autoComplete: "new-password", disabled: busy || locked })))
295
+ : null,
296
+ form.provider === "graph"
297
+ ? h("div", { "data-testid": "mail-graph" },
298
+ h("div", { className: "scalio-mail-grid" },
299
+ h(Field, { id: "mail-graph-tenant", label: L.tenantId }, input("mail-graph-tenant", form.graph.tenant_id, part("graph", "tenant_id"),
300
+ { maxLength: 36, placeholder: "00000000-0000-0000-0000-000000000000", className: "scalio-input scalio-mono", disabled: busy })),
301
+ h(Field, { id: "mail-graph-client", label: L.clientId }, input("mail-graph-client", form.graph.client_id, part("graph", "client_id"),
302
+ { maxLength: 36, placeholder: "00000000-0000-0000-0000-000000000000", className: "scalio-input scalio-mono", disabled: busy })),
303
+ h(Field, { id: "mail-graph-secret", label: L.clientSecret }, input("mail-graph-secret", form.graph.client_secret, part("graph", "client_secret"),
304
+ { type: "password", maxLength: 500, autoComplete: "new-password", disabled: busy })),
305
+ h(Field, { id: "mail-graph-sender", label: L.sender }, input("mail-graph-sender", form.graph.sender, part("graph", "sender"),
306
+ { type: "email", maxLength: 254, placeholder: "it@example.com", disabled: busy }))),
307
+ h("p", { className: "scalio-settings-help" }, props.graphHint || L.graphHint))
308
+ : null,
309
+ h(Notice, { msg: m.msg, testId: "mail-message" }),
310
+ h("div", { className: "scalio-settings-section-footer" },
311
+ h("button", { type: "submit", className: "scalio-btn is-primary", disabled: busy || locked, "data-testid": "mail-save" },
312
+ h(Icons.Check, { className: "scalio-icon" }), L.save))
313
+ )
314
+ );
315
+
316
+ const testBlock = h(
317
+ SettingsSection,
318
+ { id: "mail-test", title: L.testTitle, description: L.testHint, testId: "mail-test-section" },
319
+ h("div", { className: "scalio-mail-test" },
320
+ input("mail-test-to", to, setTo, { type: "email", placeholder: L.recipient, "aria-label": L.recipient, maxLength: 254 }),
321
+ h("button", { type: "button", className: "scalio-btn", onClick: test, disabled: testing || form.provider === "off", "data-testid": "mail-test" },
322
+ h(Icons.CornerDownLeft, { className: "scalio-icon" }), L.sendTest)),
323
+ h(Notice, { msg: testMsg, testId: "mail-test-message" })
324
+ );
325
+
326
+ const outbox = showOutbox
327
+ ? h(
328
+ SettingsSection,
329
+ { id: "mail-outbox", title: L.outboxTitle, description: L.outboxHint, testId: "mail-outbox-section" },
330
+ h("div", { className: "scalio-settings-section-footer" },
331
+ h("button", { type: "button", className: "scalio-btn is-ghost", onClick: loadOutbox, "data-testid": "mail-outbox-refresh" }, L.refresh)),
332
+ rows.length === 0
333
+ ? h("p", { className: "scalio-settings-text", "data-testid": "mail-outbox-empty" }, L.outboxEmpty)
334
+ : h("div", { className: "scalio-mail-outbox" },
335
+ h("table", { "data-testid": "mail-outbox" },
336
+ h("tbody", null, rows.map((r) => h("tr", { key: r.id },
337
+ h("td", { className: "scalio-mail-time" }, fmtTime(r.created_at, lang)),
338
+ h("td", null, r.to),
339
+ h("td", null, r.subject, r.error ? h("span", { className: "scalio-settings-help is-error" }, r.error) : null),
340
+ h("td", { className: "scalio-mail-state" },
341
+ h("span", { className: `scalio-badge is-${{ pending: "running", sent: "ok", failed: "error" }[r.status] || "neutral"}` },
342
+ L.states[r.status] || r.status)))))))
343
+ )
344
+ : null;
345
+
346
+ return h(React.Fragment, null, transport, testBlock, props.children || null, outbox);
347
+ }
348
+
349
+ // Props: client (mailApi), lang, labels, notify, formatError, editor (the app's rich text editor: a component with
350
+ // {value, onChange, testId}; without it a text field), delay (ms before the preview reloads, default 450).
351
+ function MailTemplates(props) {
352
+ const { client, lang } = props;
353
+ const L = mailLabels(lang, props.labels);
354
+ const m = useMessages(props);
355
+ const [data, setData] = React.useState(null);
356
+ const [kind, setKind] = React.useState("");
357
+ const [tlang, setTlang] = React.useState("");
358
+ const [subject, setSubject] = React.useState("");
359
+ const [body, setBody] = React.useState("");
360
+ const [busy, setBusy] = React.useState(false);
361
+ const [showPreview, setShowPreview] = React.useState(true);
362
+ const [preview, setPreview] = React.useState({ subject: "", html: "" });
363
+ const [provider, setProvider] = React.useState(null);
364
+ const delay = props.delay == null ? 450 : props.delay;
365
+
366
+ const apply = (d, k, l) => {
367
+ setData(d);
368
+ const kk = k || (d.kinds[0] && d.kinds[0].code) || "";
369
+ const ll = l || d.language || "de";
370
+ setKind(kk);
371
+ setTlang(ll);
372
+ const meta = d.kinds.find((x) => x.code === kk);
373
+ const t = meta && meta.texts[ll];
374
+ setSubject(t ? t.subject : "");
375
+ setBody(t ? (props.editor ? textToHtml(t.body) : t.body) : "");
376
+ };
377
+
378
+ React.useEffect(() => {
379
+ let alive = true;
380
+ client.templates().then((d) => alive && apply(d)).catch((e) => alive && m.fail(e));
381
+ if (client.settings) client.settings().then((s) => alive && setProvider(s.provider)).catch(() => {});
382
+ return () => { alive = false; };
383
+ }, [client]); // eslint-disable-line react-hooks/exhaustive-deps
384
+
385
+ React.useEffect(() => {
386
+ if (!showPreview || !kind || !tlang) return undefined;
387
+ let alive = true;
388
+ const t = setTimeout(() => {
389
+ client.preview({ kind, lang: tlang, subject, body }).then((p) => alive && setPreview(p)).catch(() => {});
390
+ }, delay);
391
+ return () => { alive = false; clearTimeout(t); };
392
+ }, [client, showPreview, kind, tlang, subject, body, delay]);
393
+
394
+ const section = (children) => h(SettingsSection, { id: "mail-templates", title: L.templatesTitle, description: L.templatesHint, testId: "mail-templates" }, children);
395
+ if (!data) return section(h(Notice, { msg: m.msg, testId: "mail-templates-message" }));
396
+
397
+ const meta = data.kinds.find((x) => x.code === kind) || data.kinds[0];
398
+ const text = meta.texts[tlang] || {};
399
+ const run = async (fn, okText) => {
400
+ setBusy(true);
401
+ m.clear();
402
+ try {
403
+ const r = await fn();
404
+ if (okText) m.ok(typeof okText === "function" ? okText(r) : okText);
405
+ } catch (err) {
406
+ m.fail(err);
407
+ }
408
+ setBusy(false);
409
+ };
410
+ const save = () => run(async () => apply(await client.saveTemplate(kind, tlang, { subject, body }), kind, tlang), L.templateSaved);
411
+ const reset = () => run(async () => apply(await client.resetTemplate(kind, tlang), kind, tlang), L.templateReset);
412
+ const testMe = () => run(() => client.testTemplate({ kind, lang: tlang, subject, body }), (r) => L.testSent.replace("{to}", (r && r.to) || ""));
413
+ const toggle = (on) => run(async () => {
414
+ await client.save({ notify: { [kind]: on } });
415
+ apply(await client.templates(), kind, tlang);
416
+ });
417
+ const insert = (tok) => setBody((b) => `${b || ""}{${tok}}`);
418
+
419
+ const Editor = props.editor;
420
+ const editor = Editor
421
+ ? h(Editor, { value: body, onChange: setBody, testId: "mail-template-body" })
422
+ : h("textarea", { id: "mail-template-body", className: "scalio-input scalio-textarea scalio-mail-body", rows: 14, value: body, maxLength: 50000,
423
+ "data-testid": "mail-template-body", onChange: (e) => setBody(e.target.value) });
424
+
425
+ return section(h(
426
+ "div",
427
+ { className: "scalio-settings-form" },
428
+ provider === "off" ? h("div", { className: "scalio-notice is-info", "data-testid": "mail-templates-off" }, L.off) : null,
429
+ h("div", { className: "scalio-mail-grid" },
430
+ h(Field, { id: "mail-template-kind", label: L.kind, hint: meta.description[lang === "en" ? "en" : "de"] },
431
+ select("mail-template-kind", meta.code, data.kinds.map((k) => [k.code, k.name[lang === "en" ? "en" : "de"] +
432
+ (Object.values(k.texts).some((t) => t.own) ? ` (${L.own})` : "")]), (v) => apply(data, v, tlang))),
433
+ h(Field, { id: "mail-template-lang", label: L.lang, hint: text.own ? L.custom : L.builtIn },
434
+ select("mail-template-lang", tlang, data.languages.map((l) => [l, (L.languages[l] || l) + (meta.texts[l] && meta.texts[l].own ? " ✓" : "")]),
435
+ (v) => apply(data, meta.code, v)))),
436
+ meta.switchable
437
+ ? h("label", { className: "scalio-settings-check" },
438
+ h("input", { type: "checkbox", checked: !!meta.enabled, disabled: busy, "data-testid": "mail-template-enabled", onChange: (e) => toggle(e.target.checked) }),
439
+ h("span", null, L.enabled))
440
+ : null,
441
+ h("div", null,
442
+ h("span", { className: "scalio-field-label" }, L.tokens),
443
+ h("div", { className: "scalio-mail-tokens" }, meta.tokens.map((tok) =>
444
+ h("button", { key: tok, type: "button", className: "scalio-mail-token", onClick: () => insert(tok), "data-testid": `mail-token-${tok}` }, `{${tok}}`)))),
445
+ h(Field, { id: "mail-template-subject", label: L.subject },
446
+ input("mail-template-subject", subject, setSubject, { maxLength: 300 })),
447
+ h("div", { className: "scalio-mail-editor-head" },
448
+ h("label", { className: "scalio-field-label", htmlFor: "mail-template-body" }, L.body),
449
+ h("button", { type: "button", className: "scalio-btn is-ghost", onClick: () => setShowPreview((v) => !v), "data-testid": "mail-preview-toggle" },
450
+ showPreview ? L.hidePreview : L.showPreview)),
451
+ h("div", { className: showPreview ? "scalio-mail-editor has-preview" : "scalio-mail-editor" },
452
+ h("div", { className: "scalio-mail-editor-pane" }, editor),
453
+ showPreview
454
+ ? h("div", { className: "scalio-mail-preview", "data-testid": "mail-preview" },
455
+ h("div", { className: "scalio-mail-preview-head" }, h("strong", null, L.preview), h("span", null, L.sample)),
456
+ h("div", { className: "scalio-mail-preview-subject" }, `${L.subject}: `, h("span", { "data-testid": "mail-preview-subject" }, preview.subject || "–")),
457
+ h("iframe", { title: L.preview, sandbox: "", "data-testid": "mail-preview-frame",
458
+ srcDoc: `<!doctype html><html><body style="margin:0;padding:16px;background:#fff;">${preview.html || ""}</body></html>` }))
459
+ : null),
460
+ h(Notice, { msg: m.msg, testId: "mail-templates-message" }),
461
+ h("div", { className: "scalio-settings-section-footer" },
462
+ text.own
463
+ ? h("button", { type: "button", className: "scalio-btn is-danger", onClick: reset, disabled: busy, "data-testid": "mail-template-reset" },
464
+ h(Icons.History, { className: "scalio-icon" }), L.resetTemplate)
465
+ : null,
466
+ h("button", { type: "button", className: "scalio-btn", onClick: testMe, disabled: busy || provider === "off", "data-testid": "mail-template-test" },
467
+ h(Icons.CornerDownLeft, { className: "scalio-icon" }), L.testToMe),
468
+ h("button", { type: "button", className: "scalio-btn is-primary", onClick: save, disabled: busy || !subject.trim() || !body.trim(), "data-testid": "mail-template-save" },
469
+ h(Icons.Check, { className: "scalio-icon" }), L.saveTemplate))
470
+ ));
471
+ }
472
+
473
+ module.exports = { MailTransport, MailTemplates, mailApi, mailLabels, textToHtml, MAIL_LABELS: LABELS };