diff --git a/CHANGELOG.md b/CHANGELOG.md index b04d3e0..bf45a3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Aktueller Stand +- Antwortvorlagen pro Queue mit Platzhaltern und Einfügen an der Cursorposition. +- Automatische HTML-Darstellung neuer eingehender Mails, sichere CID-Bilder und Originalansicht mit `.eml`-Download. +- HTML-Nachrichten und Signaturvorschauen folgen dem Hell-/Dunkelmodus; externe Bilder bleiben standardmäßig blockiert. + - Vollständige deutschsprachige README mit Aufnahmen aus einer isolierten Demo. - Produktions-Compose für bestehende HTTPS-Reverse-Proxys und optionales Docker-Proxy-Netzwerk. - Bootstrap-Passwort aus einer read-only Secret-Datei, starke Erstpasswörter und neutraler Administratorname. diff --git a/README.md b/README.md index 6352efe..aa7cb22 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Syncova Ticket ist ein deutschsprachiges, selbst gehostetes Ticketsystem für Te - [Ersteinrichtung](#ersteinrichtung) - [E-Mail, Abrufzeitpläne und Eingangsbestätigung](#e-mail-abrufzeitpläne-und-eingangsbestätigung) - [Signaturen und Platzhalter](#signaturen-und-platzhalter) +- [Antwortvorlagen pro Queue](#antwortvorlagen-pro-queue) - [Benutzer und Rechte](#benutzer-und-rechte) - [Updates, Backups und Wiederherstellung](#updates-backups-und-wiederherstellung) - [Konfiguration](#konfiguration) @@ -58,6 +59,12 @@ Die Übersicht trennt laufende und erledigte Tickets. Eine Suche findet Nummern, Ein Klick auf den Betreff öffnet Nachrichten, Anhänge, interne Notizen und die Aktivitätshistorie. Im Antworteditor werden ein freigegebener Queue-Absender und eine Signatur ausgewählt. Die Vorschau zeigt die aufgelösten Daten des antwortenden Benutzers. Interne Notizen bleiben intern. +Neu empfangene HTML-Mails werden standardmäßig formatiert angezeigt. **Original ansehen** öffnet eine größere Ansicht mit Klartext-Umschalter und, sofern vorhanden, Download der ursprünglichen MIME-Datei als `.eml`. Eingebettete CID-Bilder in PNG, JPEG, GIF und WebP werden ausschließlich aus den Anhängen derselben Nachricht aufgelöst. Externe HTTPS-Bilder sind zunächst blockiert und lassen sich pro Nachricht ausdrücklich freigeben. HTML-Ansicht und Signaturvorschau folgen dem gewählten Hell-/Dunkelmodus; im Dunkelmodus werden weiße Hintergründe und unlesbare Textfarben angepasst. Die Farben eingebetteter Bilddateien bleiben erhalten. + +![Originalansicht mit eingebettetem Bild im Dunkelmodus](docs/images/message-original.jpg) + +HTML und MIME-Originale werden erst seit diesem Update beim Empfang gespeichert. Für bereits früher importierte Nachrichten lässt sich ein verworfener HTML-Teil nicht nachträglich rekonstruieren; dort wird der bisher gespeicherte Inhalt angezeigt. Die HTML-Vorschau sehr großer Nachrichten wird auf 2 MiB begrenzt, während die gespeicherte Originaldatei vollständig heruntergeladen werden kann. Aktive Inhalte, Skripte und unsichere Bildformate werden nicht ausgeführt. + ![Ticketverlauf mit interner Notiz, empfangenem Anhang und Antworteditor](docs/images/ticket-detail.png) **Manuelles Ticket erstellen** erfasst Kundenname, E-Mail, Betreff und Beschreibung ohne vorherige E-Mail. Dafür sind Lesen und Antworten in der Queue erforderlich. Es entsteht keine automatische Kunden-Eingangsbestätigung. Wiederholtes Speichern desselben Auftrags erzeugt kein zweites Ticket. @@ -256,15 +263,25 @@ Bestehende Vorlagen mit `{%user.firstName%}`, `{%user.lastName%}`, `{%user.phone

``` -HTML wird bereinigt, eingefügte Werte werden maskiert und nicht rekursiv interpretiert. Skripte, Eventhandler und gefährliche URLs werden entfernt. Die Vorschau läuft isoliert und lädt keine externen Bilder; erlaubte HTTPS-Logos bleiben im versendeten HTML erhalten. Jede HTML-Mail besitzt eine Klartextalternative. +HTML wird bereinigt, eingefügte Werte werden maskiert und nicht rekursiv interpretiert. Skripte, Eventhandler und gefährliche URLs werden entfernt. Die Vorschau läuft isoliert und lädt keine externen Bilder; erlaubte HTTPS-Logos bleiben im versendeten HTML erhalten. Jede HTML-Mail besitzt eine Klartextalternative. Auch eine Vorlage mit ausdrücklich weißem Hintergrund wird in der dunklen Vorschau lesbar auf Anthrazit dargestellt.
HTML-Editor und Platzhaltervorschau ansehen -![HTML-Signatur mit gruppierten Platzhaltern und aufgelöster Vorschau](docs/images/signatures.png) +![HTML-Signatur mit aufgelöster Vorschau im Dunkelmodus](docs/images/signature-dark.jpg)
+## Antwortvorlagen pro Queue + +Unter **Einstellungen → Queue → Antwortvorlagen** lassen sich vordefinierte Antworttexte anlegen, bearbeiten und entfernen. Die Verwaltung benötigt „Queue konfigurieren“. Pro Queue sind bis zu 100 Vorlagen mit eindeutigem Namen (höchstens 100 Zeichen) und bis zu 20.000 Zeichen Antworttext möglich. Die Daten werden dauerhaft im bestehenden Volume gespeichert und Änderungen protokolliert. + +Im Ticket eine **Antwortvorlage** auswählen und **Vorlage einfügen** anklicken. Der Text ersetzt die aktuelle Textauswahl bzw. wird an der Cursorposition ergänzt; bestehende Entwürfe bleiben dadurch bearbeitbar. Die Nachricht wird dabei nicht versendet. Alle Signatur-Platzhalter aus der Tabelle oben können auch in Antwortvorlagen verwendet werden, beispielsweise `{kunde.name}`, `{ticket.nummer}` und `{benutzer.name}`. Aufgelöst werden die tatsächlichen Daten des Tickets und des antwortenden Benutzers. Die Signatur bleibt separat und wird beim Versand angehängt. + +Vorlagen können ausschließlich in Tickets ihrer eigenen Queue eingefügt werden. Zum Einfügen sind Lesen und Antworten in dieser Queue erforderlich. Bei einem Queue-Wechsel gilt anschließend die Vorlagenauswahl der neuen Queue. + +![Antwortvorlage im Ticket mit aufgelösten Kunden- und Ticketdaten](docs/images/reply-templates.jpg) + ## Benutzer und Rechte Berechtigungen sind eine **Union der Erlaubnisse aller Gruppen**. Eine leere Auswahl gewährt keinen Zugriff. Queue-Rechte steuern Lesen, Antworten, Notizen, Status, Zuständigkeit, Verschieben, Wareneingang, Mailkonfiguration und Signaturen. Die Benutzerverwaltung ist workspaceweit. „Alle Queues“ gilt auch für neu angelegte Queues. @@ -284,7 +301,7 @@ Queue-Löschung erfordert die Bestätigung des Namens. Vorhandene Tickets müsse ## Updates, Backups und Wiederherstellung -Alle Anwendungsdaten liegen im benannten Volume `_syncova_data`: SQLite, Nachrichten, Anhänge als BLOBs, Benutzer, Gruppen, Signaturen, Mailkonfiguration, Sitzungen, Termine, Benachrichtigungen, Audit und Versandwarteschlange sowie `smtp.key`. +Alle Anwendungsdaten liegen im benannten Volume `_syncova_data`: SQLite, Nachrichten einschließlich gespeicherter MIME-Originale und HTML, Anhänge und CID-Zuordnungen, Benutzer, Gruppen, Signaturen, Antwortvorlagen, Mailkonfiguration, Sitzungen, Termine, Benachrichtigungen, Audit und Versandwarteschlange sowie `smtp.key`. Vor einem Update eine Sicherung erstellen. Für planbare Releases `SYNCOVA_IMAGE` in `.env.docker` auf einen festen `sha-...`-Tag oder veröffentlichten Versionstag setzen: diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index cbdd481..ed1aa2f 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -52,7 +52,7 @@ curl --fail https://tickets.meine-domain.de/healthz Beim reinen Docker-Proxy-Netzwerk entfällt der Loopback-Test auf dem Host; der Compose-Healthcheck läuft weiterhin im Container. `/healthz` prüft den Server und eine SQLite-Abfrage, **nicht** die Zustellbarkeit von SMTP, die Erreichbarkeit von IMAP oder freie Plattenkapazität. -Zusätzlich überwachen: Zertifikatablauf am Proxy, Dateisystemkapazität und Volume-Wachstum, Container-Neustarts, RAM-Auslastung, letzte erfolgreiche Queue-Abrufe, blockierte/unklare Versandaufträge und Alter der letzten externen Sicherung. Logs sind auf drei Dateien mit je 10 MB begrenzt. Anhänge wachsen mit der SQLite-Datenbank; es gibt keine automatische Aufbewahrungs- oder Löschregel für Tickets. +Zusätzlich überwachen: Zertifikatablauf am Proxy, Dateisystemkapazität und Volume-Wachstum, Container-Neustarts, RAM-Auslastung, letzte erfolgreiche Queue-Abrufe, blockierte/unklare Versandaufträge und Alter der letzten externen Sicherung. Logs sind auf drei Dateien mit je 10 MB begrenzt. Anhänge und seit dem HTML-Update zusätzlich gespeicherte MIME-Originaldateien wachsen mit der SQLite-Datenbank; es gibt keine automatische Aufbewahrungs- oder Löschregel für Tickets. Antwortvorlagen, HTML und Inline-Bildzuordnungen sind Bestandteil derselben Datenbanksicherung und werden beim Import mit übernommen. Das Stoppsignal beendet neue Abrufzyklen, lässt laufende HTTP-/Mailverarbeitung bis zu 35 Sekunden auslaufen und schließt die Datenbank. Compose gewährt 45 Sekunden. Bei länger laufenden oder abgebrochenen SMTP-Vorgängen bleibt die Prüfung auf unklare Zustellung beim nächsten Start relevant. diff --git a/docs/images/message-original.jpg b/docs/images/message-original.jpg new file mode 100644 index 0000000..0e54882 Binary files /dev/null and b/docs/images/message-original.jpg differ diff --git a/docs/images/reply-templates.jpg b/docs/images/reply-templates.jpg new file mode 100644 index 0000000..772fdd7 Binary files /dev/null and b/docs/images/reply-templates.jpg differ diff --git a/docs/images/signature-dark.jpg b/docs/images/signature-dark.jpg new file mode 100644 index 0000000..a6da9fc Binary files /dev/null and b/docs/images/signature-dark.jpg differ diff --git a/server/app.js b/server/app.js index c3e7122..12ae9a1 100644 --- a/server/app.js +++ b/server/app.js @@ -156,6 +156,27 @@ export function createApp(db) { }) res.send(a.content) }) + app.get('/api/messages/:id/view', (req, res) => res.json(s.viewMessage(req.user, req.params.id))) + app.get('/api/messages/:id/original', (req, res) => { + const m = s.message(req.user, req.params.id), + original = s.get('SELECT source FROM message_originals WHERE message_id=?', m.id) + if (!original?.source) + throw new HttpError(404, 'Für diese Nachricht liegt keine Originaldatei vor.') + res.set({ + 'Content-Type': 'application/octet-stream', + 'Content-Disposition': `attachment; filename="nachricht-${m.ticket_id}.eml"`, + 'Content-Security-Policy': "sandbox; default-src 'none'", + }) + res.send(original.source) + }) + app.put('/api/queues/:id/templates', (req, res) => + res.json(s.saveTemplates(req.user, req.params.id, req.body.templates)), + ) + app.post('/api/tickets/:id/templates/:templateId', (req, res) => + res.json( + s.renderTemplate(req.user, Number(req.params.id), req.params.templateId, req.body.from), + ), + ) app.get('/api/notifications', (req, res) => res.json(s.notifications(req.user))) app.post('/api/notifications/read', (req, res) => { s.readNotifications(req.user, req.body.id) diff --git a/server/content.js b/server/content.js index 0863bcc..f280775 100644 --- a/server/content.js +++ b/server/content.js @@ -7,7 +7,7 @@ export const escapeHtml = (value) => /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c], ) -export function safeHtml(html) { +export function safeHtml(html, options = {}) { return sanitizeHtml(html, { allowedTags: [ 'p', @@ -32,6 +32,20 @@ export function safeHtml(html) { 'th', 'img', 'hr', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'blockquote', + 'pre', + 'code', + 'dl', + 'dt', + 'dd', + 'tfoot', + 'font', ], allowedAttributes: { '*': ['style'], @@ -39,9 +53,11 @@ export function safeHtml(html) { img: ['src', 'alt', 'width', 'height'], td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan'], + table: ['width', 'cellpadding', 'cellspacing', 'border'], + font: ['color', 'face', 'size'], }, allowedSchemes: ['https', 'http', 'mailto', 'tel'], - allowedSchemesByTag: { img: ['https', 'data'] }, + allowedSchemesByTag: { img: options.cid ? ['https', 'data', 'cid'] : ['https', 'data'] }, allowProtocolRelative: false, allowedStyles: { '*': { @@ -125,6 +141,12 @@ export function normaliseAttachments(values = []) { ? a.mime : 'application/octet-stream', content, + contentId: + typeof a.contentId === 'string' && + a.contentId.length <= 998 && + !/[\r\n\0]/.test(a.contentId) + ? a.contentId.trim().replace(/^<|>$/g, '') + : '', } }) } diff --git a/server/db.js b/server/db.js index 0bae442..7d44c11 100644 --- a/server/db.js +++ b/server/db.js @@ -55,6 +55,9 @@ export function openDb(file = process.env.DB_PATH || 'data/syncova.db') { CREATE TABLE IF NOT EXISTS messages(id TEXT PRIMARY KEY,ticket_id INTEGER REFERENCES tickets(id),kind TEXT NOT NULL,sender TEXT NOT NULL,recipient TEXT NOT NULL,body TEXT NOT NULL,message_id TEXT UNIQUE NOT NULL,refs TEXT NOT NULL DEFAULT '[]',created_at TEXT NOT NULL,delivery TEXT NOT NULL DEFAULT 'received'); CREATE TABLE IF NOT EXISTS attachments(id TEXT PRIMARY KEY,message_id TEXT REFERENCES messages(id),name TEXT NOT NULL,mime TEXT NOT NULL,content BLOB NOT NULL); CREATE TABLE IF NOT EXISTS message_html(message_id TEXT PRIMARY KEY REFERENCES messages(id),html TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS message_originals(message_id TEXT PRIMARY KEY REFERENCES messages(id),html TEXT,source BLOB); + CREATE TABLE IF NOT EXISTS attachment_inline(attachment_id TEXT PRIMARY KEY REFERENCES attachments(id),content_id TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS reply_templates(id TEXT PRIMARY KEY,queue_id TEXT NOT NULL REFERENCES queues(id),name TEXT NOT NULL,body TEXT NOT NULL,position INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS audits(id INTEGER PRIMARY KEY AUTOINCREMENT,ticket_id INTEGER REFERENCES tickets(id),queue_id TEXT,actor TEXT NOT NULL,action TEXT NOT NULL,entity TEXT NOT NULL,before_value TEXT,after_value TEXT,created_at TEXT NOT NULL); CREATE TRIGGER IF NOT EXISTS audit_no_update BEFORE UPDATE ON audits BEGIN SELECT RAISE(ABORT,'Audit is immutable'); END; CREATE TRIGGER IF NOT EXISTS audit_no_delete BEFORE DELETE ON audits BEGIN SELECT RAISE(ABORT,'Audit is immutable'); END; diff --git a/server/inbound.js b/server/inbound.js index e03a3c2..0e215af 100644 --- a/server/inbound.js +++ b/server/inbound.js @@ -300,7 +300,7 @@ export class InboundWorker { const message = await client.fetchOne(uid, { source: true }, { uid: true }) if (!message) continue if (message.source.length > 20 * 1024 * 1024) throw Error('MessageTooLarge') - const p = await simpleParser(message.source) + const p = await simpleParser(message.source, { keepCidLinks: true }) const to = [...(p.to?.value || []), ...(p.cc?.value || [])] .map((x) => x.address) .filter(Boolean) @@ -325,6 +325,8 @@ export class InboundWorker { to, subject: p.subject, body: p.text || '(HTML-Nachricht ohne Textalternative)', + html: typeof p.html === 'string' ? p.html : null, + source: Buffer.from(message.source), inReplyTo: p.inReplyTo, references: typeof p.references === 'string' ? [p.references] : p.references || [], autoSubmitted: p.headers.get('auto-submitted'), @@ -333,6 +335,7 @@ export class InboundWorker { name: a.filename, mime: a.contentType, content: a.content.toString('base64'), + contentId: a.contentId || a.cid, })), } const result = this.s.tx(() => { diff --git a/server/message-view.js b/server/message-view.js new file mode 100644 index 0000000..43c63b9 --- /dev/null +++ b/server/message-view.js @@ -0,0 +1,76 @@ +import sanitizeHtml from 'sanitize-html' +import { safeHtml, escapeHtml } from './content.js' + +function raster(mime, content) { + if (mime === 'image/png') + return content.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) + if (mime === 'image/jpeg') return content[0] === 255 && content[1] === 216 && content[2] === 255 + if (mime === 'image/gif') return ['GIF87a', 'GIF89a'].includes(content.subarray(0, 6).toString()) + if (mime === 'image/webp') + return ( + content.subarray(0, 4).toString() === 'RIFF' && content.subarray(8, 12).toString() === 'WEBP' + ) + return false +} +export function messageView(s, m) { + const original = s.get( + 'SELECT html,source IS NOT NULL has_source FROM message_originals WHERE message_id=?', + m.id, + ) + const source = + original?.html || s.get('SELECT html FROM message_html WHERE message_id=?', m.id)?.html + const markup = source ? Buffer.from(source, 'utf8') : null + const truncated = !!markup && markup.length > 2 * 1024 * 1024 + const clean = source + ? safeHtml(markup.subarray(0, 2 * 1024 * 1024).toString('utf8'), { cid: true }) + : `
${escapeHtml(m.body).replace(/\n/g, '
')}
` + const attachments = s.all( + 'SELECT a.mime,a.content,i.content_id FROM attachment_inline i JOIN attachments a ON a.id=i.attachment_id WHERE a.message_id=?', + m.id, + ) + let bytes = 0, + blockedInline = 0, + remoteImages = 0 + const html = sanitizeHtml(clean, { + allowedTags: false, + allowedAttributes: false, + allowVulnerableTags: true, + allowedSchemes: ['https', 'http', 'mailto', 'tel', 'data'], + allowedSchemesByTag: { img: ['https', 'data'] }, + allowProtocolRelative: false, + transformTags: { + img: (tag, attrs) => { + if (attrs.src?.startsWith('cid:')) { + let cid = attrs.src.slice(4) + try { + cid = decodeURIComponent(cid) + } catch {} + const matching = attachments.filter((a) => a.content_id === cid) + const a = matching.length === 1 ? matching[0] : null + if (a && raster(a.mime, a.content) && bytes + a.content.length <= 20 * 1024 * 1024) { + bytes += a.content.length + attrs.src = `data:${a.mime};base64,${a.content.toString('base64')}` + } else { + delete attrs.src + attrs.alt = attrs.alt || 'Eingebettetes Bild nicht verfügbar' + blockedInline++ + } + } else if (attrs.src?.startsWith('https:')) remoteImages++ + return { tagName: tag, attribs: attrs } + }, + a: (tag, attrs) => ({ + tagName: tag, + attribs: { ...attrs, target: '_blank', rel: 'noopener noreferrer' }, + }), + }, + }) + return { + html, + text: m.body, + hasSource: !!original?.has_source, + hasHtml: !!source, + truncated, + blockedInline, + remoteImages, + } +} diff --git a/server/service.js b/server/service.js index cf5d9d9..27a2a57 100644 --- a/server/service.js +++ b/server/service.js @@ -2,6 +2,8 @@ import { scheduledTime } from './time.js' import { acknowledge } from './mail-config.js' import { safeHtml, composeContent, normaliseAttachments } from './content.js' import { signatureContext, validateSignatureTemplate } from './signature-placeholders.js' +import { expandSignature } from './signature-placeholders.js' +import { messageView } from './message-view.js' import { uid, now, actions, behaviors, createQueue, passwordHash } from './db.js' export class HttpError extends Error { constructor(status, message) { @@ -80,6 +82,10 @@ export class Service { body: s.format === 'html' ? safeHtml(s.body) : s.body, })), statuses: this.all('SELECT * FROM statuses WHERE queue_id=? ORDER BY position', id), + templates: this.all( + 'SELECT id,name,body FROM reply_templates WHERE queue_id=? ORDER BY position,id', + id, + ), } } openStatus(q) { @@ -149,6 +155,12 @@ export class Service { ).map((m) => ({ ...m, html: this.get('SELECT html FROM message_html WHERE message_id=?', m.id)?.html || null, + has_html: !!( + this.get( + 'SELECT 1 FROM message_originals WHERE message_id=? AND html IS NOT NULL', + m.id, + ) || this.get('SELECT 1 FROM message_html WHERE message_id=?', m.id) + ), attachments: this.all( 'SELECT id,name,mime,length(content) size FROM attachments WHERE message_id=?', m.id, @@ -521,6 +533,16 @@ export class Service { } ingest(data, expectedQueue) { return this.tx(() => { + if ( + data.html != null && + (typeof data.html !== 'string' || data.html.length > 20 * 1024 * 1024) + ) + fail(400, 'Ungültiger HTML-Inhalt (maximal 20 MB).') + if ( + data.source != null && + (!Buffer.isBuffer(data.source) || data.source.length > 20 * 1024 * 1024) + ) + fail(400, 'Ungültige Originalnachricht (maximal 20 MB).') if ( !data.messageId || data.messageId.length > 998 || @@ -593,8 +615,17 @@ export class Service { at, ) for (const a of normaliseAttachments(data.attachments)) { - this.run('INSERT INTO attachments VALUES(?,?,?,?,?)', uid(), id, a.name, a.mime, a.content) + const aid = uid() + this.run('INSERT INTO attachments VALUES(?,?,?,?,?)', aid, id, a.name, a.mime, a.content) + if (a.contentId) this.run('INSERT INTO attachment_inline VALUES(?,?)', aid, a.contentId) } + if (data.html || data.source) + this.run( + 'INSERT INTO message_originals VALUES(?,?,?)', + id, + data.html || null, + data.source || null, + ) this.run('UPDATE tickets SET updated_at=?,revision=revision+1 WHERE id=?', at, t.id) this.audit( 'E-Mail-Adapter', @@ -773,6 +804,7 @@ export class Service { } } this.run('DELETE FROM queue_mail WHERE queue_id=?', id) + this.run('DELETE FROM reply_templates WHERE queue_id=?', id) this.run('DELETE FROM queue_inbound WHERE queue_id=?', id) this.run('DELETE FROM inbound_receipts WHERE queue_id=?', id) this.run('UPDATE statuses SET active=0 WHERE queue_id=?', id) @@ -824,6 +856,64 @@ export class Service { this.audit(user.id, 'Signaturen geändert', id, q.signatures, clean, null, id) }) } + message(user, id) { + const m = + this.get('SELECT * FROM messages WHERE id=?', id) || fail(404, 'Nachricht nicht gefunden.') + this.ticket(user, m.ticket_id) + return m + } + viewMessage(user, id) { + return messageView(this, this.message(user, id)) + } + saveTemplates(user, id, templates) { + return this.tx(() => { + this.require(user, id, 'queue') + const q = this.queue(id) + if ( + !Array.isArray(templates) || + templates.length > 100 || + templates.some( + (t) => + !t || + typeof t.name !== 'string' || + !t.name.trim() || + t.name.length > 100 || + typeof t.body !== 'string' || + !t.body.trim() || + t.body.length > 20000, + ) + ) + fail(400, 'Maximal 100 Vorlagen mit Name (100 Zeichen) und Text (20.000 Zeichen) erlaubt.') + const seen = new Set(), + names = new Set() + const clean = templates.map((t) => { + if (t.id && (!q.templates.some((v) => v.id === t.id) || seen.has(t.id))) + fail(400, 'Vorlage gehört nicht zur Queue oder Kennung ist doppelt.') + const name = t.name.trim() + if (names.has(name.toLowerCase())) + fail(400, 'Vorlagennamen müssen innerhalb einer Queue eindeutig sein.') + names.add(name.toLowerCase()) + if (t.id) seen.add(t.id) + validateSignatureTemplate(t.body) + return { id: t.id || uid(), name, body: t.body } + }) + this.run('DELETE FROM reply_templates WHERE queue_id=?', id) + clean.forEach((t, i) => + this.run('INSERT INTO reply_templates VALUES(?,?,?,?,?)', t.id, id, t.name, t.body, i), + ) + this.audit(user.id, 'Antwortvorlagen geändert', id, q.templates, clean, null, id) + return clean + }) + } + renderTemplate(user, id, templateId, from) { + const t = this.ticket(user, id, 'reply'), + q = this.queue(t.queue_id), + template = q.templates.find((v) => v.id === templateId) + if (!template) fail(404, 'Antwortvorlage gehört nicht zur Ticket-Queue.') + if (!q.addresses.some((a) => a.outgoing && a.email === from)) + fail(400, 'Absender ist für diese Queue nicht freigegeben.') + return { text: expandSignature(template.body, signatureContext(this, user, q, t, from)) } + } saveStatuses(user, id, statuses, mapping = {}) { return this.tx(() => { this.require(user, id, 'statuses') diff --git a/server/signature-placeholders.js b/server/signature-placeholders.js index 1e3bb91..6e741ef 100644 --- a/server/signature-placeholders.js +++ b/server/signature-placeholders.js @@ -62,7 +62,7 @@ export function validateSignatureTemplate(body) { if (unknown.length) throw new HttpError( 400, - `Unbekannte Signatur-Platzhalter: ${[...new Set(unknown)].map((k) => '{' + k + '}').join(', ')}`, + `Unbekannte Platzhalter: ${[...new Set(unknown)].map((k) => '{' + k + '}').join(', ')}`, ) } export function expandSignature(body, values, escape = (v) => v) { diff --git a/src/App.tsx b/src/App.tsx index 4daa0c2..00e2722 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState, type ReactNode } from 'react' +import { useEffect, useState, useRef, type ReactNode } from 'react' import { Inbox, Search, @@ -40,6 +40,8 @@ import { api, date, number } from './api' import { SettingsPage } from './Settings' import { HtmlPreview } from './HtmlPreview' import { AttachmentPicker } from './AttachmentPicker' +import { MessageContent } from './MessageContent' +import { ReplyTemplates } from './ReplyTemplates' type Data = any export function Field({ label, children }: { label: string; children: ReactNode }) { return ( @@ -56,13 +58,13 @@ export function Select({ value, onChange, children, ...props }: any) { ) } -export function Modal({ open, onClose, title, children }: any) { +export function Modal({ open, onClose, title, children, wide = false }: any) { return ( !e.open && onClose()}> - + {title} @@ -916,6 +918,7 @@ function ManualTicketModal({ open, onClose, queues, run, onCreated }: any) { ) } function TicketDetail({ id, boot, can, onBack, run }: any) { + const bodyEditor = useRef(null) const [t, setT] = useState(null), [tab, setTab] = useState('messages'), [kind, setKind] = useState('outgoing'), @@ -1072,17 +1075,7 @@ function TicketDetail({ id, boot, can, onBack, run }: any) { {m.kind === 'note' &&
Nur intern sichtbar
} - {m.html ? ( -
- -
- Klartext anzeigen -
{m.body}
-
-
- ) : ( -
{m.body}
- )} + {m.attachments.map((a: Data) => ( @@ -1188,7 +1181,28 @@ function TicketDetail({ id, boot, can, onBack, run }: any) { Diese Notiz bleibt intern und wird niemals an Kunden versendet. )} + {kind === 'outgoing' && ( + { + const el = bodyEditor.current + if (!el) return + const start = el.selectionStart, + end = el.selectionEnd + setBody( + (current: string) => current.slice(0, start) + text + current.slice(end), + ) + requestAnimationFrame(() => { + el.focus() + el.setSelectionRange(start + text.length, start + text.length) + }) + }} + /> + )}