`,
at,
)
+ db.prepare(
+ `INSERT INTO mail_imports(queue_id,message_id,message_row_id)
+ SELECT ?,message_id,id FROM messages WHERE ticket_id=?`,
+ ).run(q, id)
})
}
})()
diff --git a/server/inbound.js b/server/inbound.js
index a21dabb..9ad0f5f 100644
--- a/server/inbound.js
+++ b/server/inbound.js
@@ -239,6 +239,7 @@ export class InboundWorker {
this.running.add(id)
let client,
imported = 0,
+ routed = 0,
failed = 0,
pending = 0,
flagFailed = 0,
@@ -429,6 +430,7 @@ export class InboundWorker {
})
failures.delete(uid)
if (!result.ignored && !result.duplicate) imported++
+ routed += result.ticket_ids?.length || (result.ticket_id ? 1 : 0)
await markRead(uid, mailIdentity(meta.envelope, parsed, size))
} catch (e) {
failed++
@@ -486,18 +488,19 @@ export class InboundWorker {
'Postfach abgerufen',
id,
null,
- { imported, failed, pending, retried, flagFailed },
+ { imported, routed, failed, pending, retried, flagFailed },
null,
id,
)
return {
ok: !pending && !flagFailed,
imported,
+ routed,
failed,
pending,
retried,
flagFailed,
- message: `Abruf abgeschlossen: ${imported} neue Nachricht(en), ${failed} Importfehler, ${pending} zur Wiederholung vorgemerkt, ${flagFailed} Fehler bei der Gelesen-Markierung. Weitere Nachrichten werden nach Zeitplan abgerufen.`,
+ message: `Abruf abgeschlossen: ${imported} neue Nachricht(en), ${routed} Queue-Zuordnung(en), ${failed} Importfehler, ${pending} zur Wiederholung vorgemerkt, ${flagFailed} Fehler bei der Gelesen-Markierung. Weitere Nachrichten werden nach Zeitplan abgerufen.`,
}
} catch (e) {
this.s.run(
diff --git a/server/mail-imports.js b/server/mail-imports.js
new file mode 100644
index 0000000..1eee1ce
--- /dev/null
+++ b/server/mail-imports.js
@@ -0,0 +1,64 @@
+// RFC Message-IDs identify a mail, but the same mail may be delivered to several queues.
+export function installMailImports(db) {
+ const oldUnique = db.pragma('index_list(messages)').filter(
+ (index) =>
+ index.unique &&
+ !index.partial &&
+ (() => {
+ const columns = db.prepare('SELECT name FROM pragma_index_info(?)').all(index.name)
+ return columns.length === 1 && columns[0].name === 'message_id'
+ })(),
+ )
+ const foreignKeys = db.pragma('foreign_keys', { simple: true })
+ if (oldUnique.length) db.pragma('foreign_keys = OFF')
+ const quote = (name) => '"' + name.replaceAll('"', '""') + '"'
+ try {
+ db.transaction(() => {
+ if (oldUnique.length) {
+ // SQLite validates dependent views/triggers on table rename. Preserve their exact
+ // definitions and recreate them within the same transaction; never rewrite IDs.
+ const dependents = db
+ .prepare(
+ "SELECT type,name,sql FROM sqlite_master WHERE type IN ('view','trigger') AND sql IS NOT NULL ORDER BY type DESC,name",
+ )
+ .all()
+ const indexes = db
+ .prepare(
+ "SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='messages' AND sql IS NOT NULL",
+ )
+ .all()
+ for (const object of dependents) db.exec(`DROP ${object.type} ${quote(object.name)}`)
+ db.exec(`
+ CREATE TABLE messages_next(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 NOT NULL,refs TEXT NOT NULL DEFAULT '[]',created_at TEXT NOT NULL,delivery TEXT NOT NULL DEFAULT 'received');
+ INSERT INTO messages_next(rowid,id,ticket_id,kind,sender,recipient,body,message_id,refs,created_at,delivery)
+ SELECT rowid,id,ticket_id,kind,sender,recipient,body,message_id,refs,created_at,delivery FROM messages;
+ DROP TABLE messages;
+ ALTER TABLE messages_next RENAME TO messages;
+ `)
+ for (const index of indexes)
+ if (!oldUnique.some((old) => old.name === index.name)) db.exec(index.sql)
+ for (const object of dependents) db.exec(object.sql)
+ }
+ db.exec(`
+ CREATE INDEX IF NOT EXISTS messages_external_id ON messages(message_id);
+ CREATE UNIQUE INDEX IF NOT EXISTS messages_outgoing_id ON messages(message_id) WHERE kind!='incoming';
+ `)
+ if (
+ !db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='mail_imports'").get()
+ ) {
+ db.exec(`CREATE TABLE mail_imports(queue_id TEXT NOT NULL REFERENCES queues(id),message_id TEXT NOT NULL,message_row_id TEXT NOT NULL REFERENCES messages(id),PRIMARY KEY(queue_id,message_id));
+ CREATE INDEX mail_imports_message ON mail_imports(message_row_id);
+ INSERT INTO mail_imports(queue_id,message_id,message_row_id)
+ SELECT coalesce(origin.queue_id,t.queue_id),m.message_id,m.id
+ FROM messages m JOIN tickets t ON t.id=m.ticket_id LEFT JOIN (
+ SELECT a.entity,a.queue_id FROM audits a JOIN queues q ON q.id=a.queue_id
+ JOIN (SELECT entity,min(id) id FROM audits WHERE action='E-Mail empfangen' GROUP BY entity) first ON first.id=a.id
+ ) origin ON origin.entity=m.id WHERE m.kind='incoming';`)
+ }
+ if (oldUnique.length && db.pragma('foreign_key_check').length)
+ throw Error('Mail-Migration abgebrochen: inkonsistente Datenbankverknüpfungen.')
+ })()
+ } finally {
+ if (oldUnique.length) db.pragma(`foreign_keys = ${foreignKeys ? 'ON' : 'OFF'}`)
+ }
+}
diff --git a/server/service.js b/server/service.js
index d8d3ca5..37cdc2d 100644
--- a/server/service.js
+++ b/server/service.js
@@ -451,7 +451,7 @@ export class Service {
fail(400, 'Nachricht erforderlich (max. 100.000 Zeichen).')
if (!data.key || data.key.length > 100) fail(400, 'Idempotenzschlüssel erforderlich.')
const mid = `<${data.key}@syncova.local>`
- const old = this.get('SELECT * FROM messages WHERE message_id=?', mid)
+ const old = this.get("SELECT * FROM messages WHERE message_id=? AND kind!='incoming'", mid)
if (old) {
if (old.ticket_id !== t.id) fail(409, 'Schlüssel bereits verwendet.')
return old
@@ -646,7 +646,9 @@ export class Service {
(data.precedence && ['bulk', 'junk', 'list'].includes(data.precedence))
)
return { ignored: true }
- if (this.get('SELECT id FROM messages WHERE message_id=?', data.messageId))
+ if (
+ this.get("SELECT id FROM messages WHERE message_id=? AND kind!='incoming'", data.messageId)
+ )
return { duplicate: true }
const addresses = data.to.map((a) => a.toLowerCase())
const qs = this.all('SELECT id FROM queues WHERE deleted_at IS NULL').map((q) =>
@@ -655,117 +657,145 @@ export class Service {
const matched = qs.filter((q) =>
q.addresses.some((a) => a.incoming && addresses.includes(a.email.toLowerCase())),
)
- if (matched.length !== 1) fail(400, 'Empfänger muss genau einer Queue zugeordnet sein.')
- const q = matched[0]
- if (expectedQueue && q.id !== expectedQueue)
+ if (!matched.length) fail(400, 'Kein Empfänger ist einer aktiven Queue zugeordnet.')
+ if (expectedQueue && !matched.some((q) => q.id === expectedQueue))
fail(400, 'Empfänger gehört nicht zur abrufenden Queue.')
- if (
- autoType === 'auto-generated' &&
- !this.get(
- 'SELECT 1 FROM tag_senders r JOIN queue_tags t ON t.id=r.tag_id WHERE t.queue_id=? AND r.email=?',
- q.id,
- data.from.toLowerCase(),
- )
- )
- return { ignored: true }
- if (
- qs.some((q) => q.addresses.some((a) => a.email.toLowerCase() === data.from.toLowerCase()))
- )
- return { ignored: true }
- let t
- for (const ref of [...(data.references || []), data.inReplyTo].filter(Boolean).reverse()) {
- const m = this.get(
- 'SELECT t.* FROM messages m JOIN tickets t ON t.id=m.ticket_id WHERE m.message_id=? AND m.kind!=?',
- ref,
- 'note',
- )
- if (
- m &&
- m.queue_id === q.id &&
- (m.customer.toLowerCase() === data.from.toLowerCase() ||
- this.get(
- 'SELECT 1 FROM message_recipients WHERE message_id=? AND lower(address)=?',
- this.get('SELECT id FROM messages WHERE message_id=?', ref).id,
- data.from.toLowerCase(),
- ))
- ) {
- t = m
- break
+ const results = matched.map((q) => ({
+ queue_id: q.id,
+ ...this.ingestQueue(data, q, qs, addresses, autoType),
+ }))
+ const imported = results.filter((result) => result.ticket_id)
+ if (imported.length) {
+ const primary = imported.find((result) => result.queue_id === expectedQueue) || imported[0]
+ return {
+ ticket_id: primary.ticket_id,
+ ticket_ids: imported.map((result) => result.ticket_id),
+ results,
}
}
- const isNew = !t
- const at = now()
- if (!t) {
- const s = q.statuses.find((s) => s.active && s.behavior === 'new') || this.openStatus(q.id)
- const r = this.run(
- 'INSERT INTO tickets(subject,customer,customer_name,queue_id,status_id,created_at,updated_at) VALUES(?,?,?,?,?,?,?)',
- (data.subject || '(Ohne Betreff)').slice(0, 500),
- data.from,
- data.name || data.from,
- q.id,
- s.id,
- at,
- at,
- )
- t = this.get('SELECT * FROM tickets WHERE id=?', r.lastInsertRowid)
- }
- const id = uid()
- this.run(
- 'INSERT INTO messages(id,ticket_id,kind,sender,recipient,body,message_id,refs,created_at) VALUES(?,?,?,?,?,?,?,?,?)',
- id,
- t.id,
- 'incoming',
- data.from,
- addresses.join(', '),
- data.body.slice(0, 100000),
- data.messageId,
- json(data.references || []),
- at,
+ return results.some((result) => result.duplicate)
+ ? { duplicate: true, results }
+ : { ignored: true, results }
+ })
+ }
+ ingestQueue(data, q, qs, addresses, autoType) {
+ if (
+ this.get('SELECT 1 FROM mail_imports WHERE queue_id=? AND message_id=?', q.id, data.messageId)
+ )
+ return { duplicate: true }
+ if (
+ autoType === 'auto-generated' &&
+ !this.get(
+ 'SELECT 1 FROM tag_senders r JOIN queue_tags t ON t.id=r.tag_id WHERE t.queue_id=? AND r.email=?',
+ q.id,
+ data.from.toLowerCase(),
)
- for (const a of normaliseAttachments(data.attachments)) {
- 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,
- )
- applySenderTags(this, t, data.from)
- this.run('UPDATE tickets SET updated_at=?,revision=revision+1 WHERE id=?', at, t.id)
- this.audit(
- 'E-Mail-Adapter',
- 'E-Mail empfangen',
- id,
- null,
- { messageId: data.messageId },
- t.id,
+ )
+ return { ignored: true }
+ if (qs.some((q) => q.addresses.some((a) => a.email.toLowerCase() === data.from.toLowerCase())))
+ return { ignored: true }
+ let t
+ for (const ref of [...(data.references || []), data.inReplyTo].filter(Boolean).reverse()) {
+ const m = this.get(
+ `SELECT t.*,m.id reference_id FROM messages m JOIN tickets t ON t.id=m.ticket_id
+ WHERE m.message_id=? AND m.kind!=? AND t.queue_id=?
+ ORDER BY EXISTS(SELECT 1 FROM mail_imports i WHERE i.message_row_id=m.id AND i.queue_id=?) DESC,m.created_at DESC,m.rowid DESC`,
+ ref,
+ 'note',
+ q.id,
q.id,
)
if (
- this.get('SELECT behavior FROM statuses WHERE id=?', t.status_id).behavior ===
- 'wait_customer'
+ m &&
+ m.queue_id === q.id &&
+ (m.customer.toLowerCase() === data.from.toLowerCase() ||
+ this.get(
+ 'SELECT 1 FROM message_recipients WHERE message_id=? AND lower(address)=?',
+ m.reference_id,
+ data.from.toLowerCase(),
+ ))
) {
- this.transition(t, this.openStatus(q.id), 'Kundenantwort')
- this.notify(
- t,
- 'reopened',
- `reopened:${data.messageId}`,
- 'Ticket durch Kundenantwort wieder geöffnet',
- )
+ t = m
+ break
}
+ }
+ const isNew = !t
+ const at = now()
+ if (!t) {
+ const s = q.statuses.find((s) => s.active && s.behavior === 'new') || this.openStatus(q.id)
+ const r = this.run(
+ 'INSERT INTO tickets(subject,customer,customer_name,queue_id,status_id,created_at,updated_at) VALUES(?,?,?,?,?,?,?)',
+ (data.subject || '(Ohne Betreff)').slice(0, 500),
+ data.from,
+ data.name || data.from,
+ q.id,
+ s.id,
+ at,
+ at,
+ )
+ t = this.get('SELECT * FROM tickets WHERE id=?', r.lastInsertRowid)
+ }
+ const id = uid()
+ this.run(
+ 'INSERT INTO messages(id,ticket_id,kind,sender,recipient,body,message_id,refs,created_at) VALUES(?,?,?,?,?,?,?,?,?)',
+ id,
+ t.id,
+ 'incoming',
+ data.from,
+ addresses.join(', '),
+ data.body.slice(0, 100000),
+ data.messageId,
+ json(data.references || []),
+ at,
+ )
+ this.run(
+ 'INSERT INTO mail_imports(queue_id,message_id,message_row_id) VALUES(?,?,?)',
+ q.id,
+ data.messageId,
+ id,
+ )
+ for (const a of normaliseAttachments(data.attachments)) {
+ 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,
+ )
+ applySenderTags(this, t, data.from)
+ this.run('UPDATE tickets SET updated_at=?,revision=revision+1 WHERE id=?', at, t.id)
+ this.audit(
+ 'E-Mail-Adapter',
+ 'E-Mail empfangen',
+ id,
+ null,
+ { messageId: data.messageId },
+ t.id,
+ q.id,
+ )
+ if (
+ this.get('SELECT behavior FROM statuses WHERE id=?', t.status_id).behavior === 'wait_customer'
+ ) {
+ this.transition(t, this.openStatus(q.id), 'Kundenantwort')
this.notify(
t,
- isNew ? 'new' : 'reply',
- data.messageId,
- isNew ? 'Neue Anfrage eingegangen' : 'Neue Kundenantwort',
+ 'reopened',
+ `reopened:${json([q.id, data.messageId])}`,
+ 'Ticket durch Kundenantwort wieder geöffnet',
)
- if (isNew && autoType === 'no') acknowledge(this, t, data)
- return { ticket_id: t.id }
- })
+ }
+ this.notify(
+ t,
+ isNew ? 'new' : 'reply',
+ `mail:${json([q.id, data.messageId])}`,
+ isNew ? 'Neue Anfrage eingegangen' : 'Neue Kundenantwort',
+ )
+ if (isNew && autoType === 'no') acknowledge(this, t, data)
+ return { ticket_id: t.id }
}
due() {
return this.tx(() => {
diff --git a/src/MailImportLog.tsx b/src/MailImportLog.tsx
index 25f0da1..faa5834 100644
--- a/src/MailImportLog.tsx
+++ b/src/MailImportLog.tsx
@@ -12,6 +12,7 @@ export function MailImportLog({ entry }: { entry: any }) {
return (
{info.imported || 0} neu importiert · {info.failed || 0} Importfehler
+ {info.routed != null && ` · ${info.routed} Queue-Zuordnungen`}
{info.pending != null && ` · ${info.pending} zur Wiederholung vorgemerkt`}
{!!info.flagFailed && ` · ${info.flagFailed} Fehler bei der Gelesen-Markierung`}
diff --git a/tests/multi-queue-mail.test.js b/tests/multi-queue-mail.test.js
new file mode 100644
index 0000000..b0b72c9
--- /dev/null
+++ b/tests/multi-queue-mail.test.js
@@ -0,0 +1,368 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync } from 'node:fs'
+import path from 'node:path'
+import os from 'node:os'
+import { openDb, seed, uid } from '../server/db.js'
+import { Service, HttpError } from '../server/service.js'
+import { installMailImports } from '../server/mail-imports.js'
+import { InboundWorker } from '../server/inbound.js'
+import { readMailSettings, saveMailSettings } from '../server/mail-config.js'
+process.env.SMTP_ENCRYPTION_KEY = 'a9'.repeat(32)
+function setup(file = ':memory:') {
+ const db = openDb(file)
+ seed(db)
+ const s = new Service(db)
+ return { db, s, admin: s.user('admin'), agent: s.user('leon') }
+}
+const mail = (extra = {}) => ({
+ messageId: `<${uid()}@example.org>`,
+ from: 'customer@example.org',
+ name: 'Beispielkontakt',
+ to: ['support@syncova.local', 'support.team@syncova.local', 'vertrieb@syncova.local'],
+ subject: 'Mehrere Queues',
+ body: 'Gemeinsame Anfrage',
+ ...extra,
+})
+const enable = (s, admin, q) => {
+ const c = readMailSettings(s, admin, q)
+ saveMailSettings(s, admin, q, {
+ ...c,
+ imap: { ...c.imap, enabled: true, host: 'imap.example.invalid', username: 'shared' },
+ imapPassword: 'shared-test-password',
+ })
+}
+const queueId = (s, id) => s.get('SELECT queue_id FROM tickets WHERE id=?', id).queue_id
+
+test('A multi-recipient mail creates one isolated copy per queue with originals, attachments, tags, acknowledgements and notifications', () => {
+ const { db, s, admin, agent } = setup()
+ try {
+ for (const q of ['support', 'vertrieb']) {
+ s.saveTags(admin, q, {
+ revision: 0,
+ tags: [{ name: q + '-Tag', color: '#8b5cf6', senders: ['customer@example.org'] }],
+ })
+ const c = readMailSettings(s, admin, q)
+ saveMailSettings(s, admin, q, {
+ ...c,
+ acknowledgement: {
+ enabled: true,
+ subject: 'Eingang {queue}',
+ body: 'Eingegangen bei {queue}',
+ includeSignature: false,
+ },
+ })
+ }
+ const incoming = mail({
+ html: 'Gemeinsame Anfrage
',
+ source: Buffer.from('Original MIME content'),
+ attachments: [
+ { name: 'info.txt', mime: 'text/plain', content: Buffer.from('Datei').toString('base64') },
+ ],
+ })
+ const result = s.ingest(incoming, 'vertrieb')
+ assert.equal(result.ticket_ids.length, 2)
+ assert.equal(queueId(s, result.ticket_id), 'vertrieb')
+ const [support, sales] = result.ticket_ids.sort((a, b) =>
+ queueId(s, a).localeCompare(queueId(s, b)),
+ )
+ for (const id of [support, sales]) {
+ const d = s.detail(admin, id),
+ m = d.messages.find((m) => m.kind === 'incoming')
+ assert.equal(m.message_id, incoming.messageId)
+ assert.equal(d.tags[0].name, queueId(s, id) + '-Tag')
+ assert.equal(m.attachments.length, 1)
+ const original = s.get('SELECT * FROM message_originals WHERE message_id=?', m.id)
+ assert.deepEqual(original.source, incoming.source)
+ assert.equal(original.html, incoming.html)
+ }
+ assert.equal(
+ s.all('SELECT * FROM mail_imports WHERE message_id=?', incoming.messageId).length,
+ 2,
+ )
+ assert.equal(s.all('SELECT * FROM outbox').length, 2)
+ assert.equal(
+ s.notifications(admin).filter((n) => result.ticket_ids.includes(n.ticket_id)).length,
+ 2,
+ )
+ assert.equal(
+ s.notifications(agent).filter((n) => result.ticket_ids.includes(n.ticket_id)).length,
+ 1,
+ )
+ assert.throws(() => s.detail(agent, sales), { status: 403 })
+ assert(s.ingest(incoming, 'support').duplicate)
+ assert(s.ingest(incoming).duplicate)
+ assert.equal(s.all('SELECT * FROM outbox').length, 2)
+ assert.equal(s.all('SELECT * FROM messages WHERE message_id=?', incoming.messageId).length, 2)
+ } finally {
+ db.close()
+ }
+})
+
+test('Replies with the same original Message-ID stay in their queue and reopen each matching ticket', () => {
+ const { db, s, admin } = setup()
+ try {
+ const original = mail(),
+ first = s.ingest(original)
+ const byQueue = Object.fromEntries(first.results.map((r) => [r.queue_id, r.ticket_id]))
+ for (const [q, id] of Object.entries(byQueue))
+ s.updateTicket(admin, id, {
+ status_id: s.queue(q).statuses.find((status) => status.behavior === 'wait_customer').id,
+ })
+ const reply = mail({ references: [original.messageId], subject: 'Geänderter Betreff' })
+ const result = s.ingest(reply)
+ assert.deepEqual(new Set(result.ticket_ids), new Set(first.ticket_ids))
+ for (const id of first.ticket_ids) {
+ const d = s.detail(admin, id)
+ assert.equal(d.messages.length, 2)
+ assert.equal(s.get('SELECT behavior FROM statuses WHERE id=?', d.status_id).behavior, 'open')
+ }
+ assert.equal(
+ s
+ .notifications(admin)
+ .filter((n) => n.event === 'reopened' && first.ticket_ids.includes(n.ticket_id)).length,
+ 2,
+ )
+ const outgoing = s.reply(admin, byQueue.support, {
+ key: uid(),
+ body: 'Bitte prüfen',
+ from: 'support@syncova.local',
+ cc: ['team@example.org'],
+ })
+ const cc = s.ingest(mail({ from: 'team@example.org', references: [outgoing.message_id] }))
+ assert.equal(cc.results.find((r) => r.queue_id === 'support').ticket_id, byQueue.support)
+ assert.notEqual(cc.results.find((r) => r.queue_id === 'vertrieb').ticket_id, byQueue.vertrieb)
+ } finally {
+ db.close()
+ }
+})
+
+test('Queue moves retain source-queue deduplication and another queue can still import its delivery', () => {
+ const { db, s, admin } = setup()
+ try {
+ const incoming = mail({ to: ['support@syncova.local'] })
+ const id = s.ingest(incoming).ticket_id
+ s.updateTicket(admin, id, { queue_id: 'vertrieb' })
+ assert(s.ingest(incoming, 'support').duplicate)
+ const second = s.ingest(
+ { ...incoming, to: ['support@syncova.local', 'vertrieb@syncova.local'] },
+ 'vertrieb',
+ )
+ assert.equal(second.ticket_ids.length, 1)
+ assert.notEqual(second.ticket_id, id)
+ assert.equal(queueId(s, second.ticket_id), 'vertrieb')
+ assert(s.ingest(incoming).duplicate)
+ assert.throws(() => s.ingest(mail({ to: ['support@syncova.local'] }), 'vertrieb'), {
+ status: 400,
+ })
+ } finally {
+ db.close()
+ }
+})
+
+test('Sender rules remain queue local for automatically generated mail addressed to several queues', () => {
+ const { db, s, admin } = setup()
+ try {
+ s.saveTags(admin, 'support', {
+ revision: 0,
+ tags: [{ name: 'Monitoring', color: '#8b5cf6', senders: ['customer@example.org'] }],
+ })
+ const automatic = mail({ autoSubmitted: 'auto-generated' })
+ const result = s.ingest(automatic, 'vertrieb')
+ assert.equal(result.ticket_ids.length, 1)
+ assert.equal(queueId(s, result.ticket_id), 'support')
+ assert(result.results.find((r) => r.queue_id === 'vertrieb').ignored)
+ assert.equal(s.all('SELECT * FROM outbox').length, 0)
+ assert(s.ingest(mail({ autoSubmitted: 'auto-replied' })).ignored)
+ } finally {
+ db.close()
+ }
+})
+
+test('Shared IMAP mailboxes fan out An/Cc deliveries before marking read; old failures recover and other queues do not duplicate copies', async () => {
+ const { db, s, admin } = setup()
+ try {
+ for (const q of ['support', 'vertrieb']) enable(s, admin, q)
+ const source = Buffer.from(
+ 'From: customer@example.org\r\nTo: support@syncova.local\r\nCc: vertrieb@syncova.local\r\nMessage-ID: \r\nSubject: Gemeinsam\r\n\r\nBitte bearbeiten.',
+ )
+ let seen = false,
+ marked = 0
+ const factory = () => ({
+ mailbox: { uidValidity: 1n },
+ async connect() {},
+ async getMailboxLock() {
+ return { release() {} }
+ },
+ async search() {
+ return seen ? [] : [172]
+ },
+ async fetchOne(uid, q) {
+ return q.size ? { size: source.length } : { source }
+ },
+ async messageFlagsAdd() {
+ assert.equal(
+ s.all("SELECT * FROM messages WHERE message_id=''").length,
+ 2,
+ )
+ seen = true
+ marked++
+ },
+ async logout() {},
+ close() {},
+ })
+ const worker = new InboundWorker(s, { clientFactory: factory })
+ const ingest = s.ingest.bind(s)
+ s.ingest = () => {
+ throw new HttpError(400, 'Empfänger muss genau einer Queue zugeordnet sein.')
+ }
+ assert.equal((await worker.run('support')).failed, 1)
+ assert.equal(marked, 0)
+ s.ingest = ingest
+ const recovered = await worker.run('support', { retryFailed: true })
+ assert.equal(recovered.imported, 1)
+ assert.equal(recovered.routed, 2)
+ assert.equal(s.get('SELECT count(*) n FROM inbound_failures').n, 0)
+ assert.equal((await worker.run('vertrieb')).imported, 0)
+ seen = false
+ assert.equal((await worker.run('vertrieb')).imported, 0)
+ assert.equal(
+ s.all("SELECT * FROM messages WHERE message_id=''").length,
+ 2,
+ )
+ assert.equal(marked, 2)
+ } finally {
+ db.close()
+ }
+})
+
+test('Legacy global Message-ID uniqueness migrates atomically while preserving references, FTS, audit and original queue identity', () => {
+ const folder = mkdtempSync(path.join(os.tmpdir(), 'syncova-multiqueue-'))
+ let db
+ try {
+ const initial = setup(path.join(folder, 'old.db'))
+ db = initial.db
+ const { s, admin } = initial
+ const incoming = mail({
+ to: ['support@syncova.local'],
+ html: 'Migrationsprobe
',
+ source: Buffer.from('Original'),
+ attachments: [
+ {
+ name: 'datei.txt',
+ mime: 'text/plain',
+ content: Buffer.from('Anhang').toString('base64'),
+ },
+ ],
+ })
+ const id = s.ingest(incoming).ticket_id
+ s.reply(admin, id, { key: uid(), body: 'Migrationsantwort', from: 'support@syncova.local' })
+ s.updateTicket(admin, id, { queue_id: 'vertrieb' })
+ db.exec(
+ 'DROP TABLE mail_imports; CREATE UNIQUE INDEX legacy_global_message_id ON messages(message_id)',
+ )
+ const tables = [
+ 'messages',
+ 'attachments',
+ 'attachment_inline',
+ 'message_originals',
+ 'message_recipients',
+ 'outbox',
+ 'audits',
+ 'notifications',
+ 'tickets',
+ ]
+ const before = Object.fromEntries(
+ tables.map((t) => [t, db.prepare(`SELECT rowid,* FROM ${t}`).all()]),
+ )
+ db.close()
+ db = openDb(path.join(folder, 'old.db'))
+ for (const table of tables)
+ assert.deepEqual(db.prepare(`SELECT rowid,* FROM ${table}`).all(), before[table], table)
+ assert.deepEqual(db.pragma('foreign_key_check'), [])
+ assert.equal(db.pragma('foreign_keys', { simple: true }), 1)
+ const after = new Service(db)
+ assert(after.ingest(incoming, 'support').duplicate)
+ assert.equal(
+ after.get('SELECT queue_id FROM mail_imports WHERE message_id=?', incoming.messageId)
+ .queue_id,
+ 'support',
+ )
+ assert(
+ after.searchTickets(after.user('admin'), 'Migrationsantwort').items.some((t) => t.id === id),
+ )
+ assert.throws(() => after.run('DELETE FROM audits'), /immutable/)
+ assert.throws(() => after.run('UPDATE audits SET action=?', 'changed'), /immutable/)
+ const additional = after.ingest({ ...incoming, to: ['vertrieb@syncova.local'] })
+ assert.equal(additional.ticket_ids.length, 1)
+ assert(
+ after
+ .searchTickets(after.user('admin'), 'Gemeinsame Anfrage')
+ .items.some((t) => t.id === additional.ticket_id),
+ )
+ db.close()
+ db = openDb(path.join(folder, 'old.db'))
+ assert(new Service(db).ingest(incoming).duplicate)
+ } finally {
+ db?.close()
+ assert.equal(path.dirname(path.resolve(folder)), path.resolve(os.tmpdir()))
+ assert(path.basename(folder).startsWith('syncova-multiqueue-'))
+ rmSync(folder, { recursive: true, force: true })
+ }
+})
+
+test('A failed legacy migration rolls back the schema and restores foreign-key enforcement and audit guards', () => {
+ const { db, s } = setup()
+ try {
+ s.audit('Test', 'Unveränderlich', 'migration', null, { test: true })
+ db.exec(
+ 'DROP TABLE mail_imports; CREATE UNIQUE INDEX legacy_global_message_id ON messages(message_id)',
+ )
+ db.pragma('foreign_keys=OFF')
+ s.run(
+ "INSERT INTO messages(id,ticket_id,kind,sender,recipient,body,message_id,created_at) VALUES('orphan',999999,'incoming','a@example.org','support@syncova.local','body','','2026-11-05')",
+ )
+ db.pragma('foreign_keys=ON')
+ assert.throws(() => installMailImports(db), /Mail-Migration abgebrochen/)
+ assert.equal(db.pragma('foreign_keys', { simple: true }), 1)
+ assert(db.prepare("SELECT 1 FROM sqlite_master WHERE name='legacy_global_message_id'").get())
+ assert(!db.prepare("SELECT 1 FROM sqlite_master WHERE name='mail_imports'").get())
+ assert(s.get("SELECT id FROM messages WHERE id='orphan'"))
+ assert.throws(() => s.run('DELETE FROM audits'), /immutable/)
+ } finally {
+ db.close()
+ }
+})
+
+test('A failure in any addressed queue rolls back all copies and acknowledgements so a retry cannot lose a delivery', () => {
+ const { db, s, admin } = setup()
+ try {
+ const config = readMailSettings(s, admin, 'support')
+ saveMailSettings(s, admin, 'support', {
+ ...config,
+ acknowledgement: {
+ enabled: true,
+ subject: 'Eingang',
+ body: 'Vielen Dank',
+ includeSignature: false,
+ },
+ })
+ s.run("UPDATE statuses SET active=0 WHERE queue_id='vertrieb'")
+ const incoming = mail()
+ const before = {
+ tickets: s.get('SELECT count(*) n FROM tickets').n,
+ notifications: s.get('SELECT count(*) n FROM notifications').n,
+ imports: s.get('SELECT count(*) n FROM mail_imports').n,
+ }
+ assert.throws(() => s.ingest(incoming, 'support'))
+ assert.equal(s.get('SELECT count(*) n FROM tickets').n, before.tickets)
+ assert.equal(s.get('SELECT count(*) n FROM notifications').n, before.notifications)
+ assert.equal(s.get('SELECT count(*) n FROM mail_imports').n, before.imports)
+ assert.equal(s.get('SELECT count(*) n FROM outbox').n, 0)
+ s.run("UPDATE statuses SET active=1 WHERE queue_id='vertrieb'")
+ assert.equal(s.ingest(incoming, 'support').ticket_ids.length, 2)
+ assert.equal(s.get('SELECT count(*) n FROM outbox').n, 1)
+ } finally {
+ db.close()
+ }
+})