KI-AGENT: Mailantworten und Entitätsverknüpfungen ergänzen

This commit is contained in:
2026-09-07 19:00:08 +02:00
parent 4e4466ff11
commit f3384cfc74
10 changed files with 774 additions and 30 deletions

View File

@@ -366,6 +366,11 @@ const invitePortalUser = async () => {
v-else-if="tab.label === 'Zeiten'"
:platform="platform"
/>
<EmailEntityMessages
v-else-if="tab.label === 'E-Mails'"
:entity-type="type"
:entity-id="props.item.id"
/>
<div v-else-if="tab.label === 'Wiki'" class="h-[600px] w-full overflow-hidden">
<WikiEntityWidget
:entity-type="type"
@@ -410,6 +415,11 @@ const invitePortalUser = async () => {
@updateNeeded="emit('updateNeeded')"
:platform="platform"
/>
<EmailEntityMessages
v-else-if="sub.label === 'E-Mails'"
:entity-type="type"
:entity-id="props.item.id"
/>
<!--<EntityShowSubPhases
:item="props.item"
:top-level-type="type"

View File

@@ -0,0 +1,169 @@
<script setup lang="ts">
type EntityLink = {
id: string
entityType: string
entityId: number
entityName: string
entityTypeLabel: string
}
const props = defineProps<{
messageId: string
entityLinks?: EntityLink[]
}>()
const emit = defineEmits<{
updated: [links: EntityLink[]]
}>()
const toast = useToast()
const links = ref<EntityLink[]>([])
const selectedEntityType = ref("customers")
const selectedEntityId = ref<number | null>(null)
const entityOptions = ref<Array<{ label: string; value: number }>>([])
const loadingOptions = ref(false)
const saving = ref(false)
const entityTypes = [
{ label: "Kunde", value: "customers" },
{ label: "Lieferant", value: "vendors" },
{ label: "Projekt", value: "projects" },
{ label: "Objekt", value: "plants" },
]
watch(() => props.entityLinks, (value) => {
links.value = [...(value || [])]
}, { immediate: true, deep: true })
async function loadEntityOptions() {
loadingOptions.value = true
selectedEntityId.value = null
try {
const rows = await useEntities(selectedEntityType.value).select("*")
entityOptions.value = rows.map((row: any) => {
const number = row.customerNumber || row.vendorNumber || row.projectNumber
return {
label: number ? `${number} · ${row.name}` : row.name,
value: Number(row.id),
}
})
} catch (err: any) {
entityOptions.value = []
toast.add({
title: "Entitäten konnten nicht geladen werden",
description: err?.data?.error || err?.message,
color: "error",
})
} finally {
loadingOptions.value = false
}
}
async function addLink() {
if (!selectedEntityId.value) return
saving.value = true
try {
const response = await useNuxtApp().$api(`/api/email/messages/${props.messageId}/entity-links`, {
method: "POST",
body: {
entityType: selectedEntityType.value,
entityId: selectedEntityId.value,
},
})
links.value = response.entityLinks || []
emit("updated", links.value)
selectedEntityId.value = null
toast.add({ title: "E-Mail verknüpft", color: "success" })
} catch (err: any) {
toast.add({
title: "Verknüpfen fehlgeschlagen",
description: err?.data?.error || err?.message,
color: "error",
})
} finally {
saving.value = false
}
}
async function removeLink(link: EntityLink) {
saving.value = true
try {
const response = await useNuxtApp().$api(
`/api/email/messages/${props.messageId}/entity-links/${link.entityType}/${link.entityId}`,
{ method: "DELETE" },
)
links.value = response.entityLinks || []
emit("updated", links.value)
toast.add({ title: "Verknüpfung entfernt", color: "success" })
} catch (err: any) {
toast.add({
title: "Entfernen fehlgeschlagen",
description: err?.data?.error || err?.message,
color: "error",
})
} finally {
saving.value = false
}
}
watch(selectedEntityType, loadEntityOptions, { immediate: true })
</script>
<template>
<div class="mt-4 rounded-lg border border-(--ui-border) bg-(--ui-bg-muted) p-3">
<div class="flex flex-wrap items-center gap-2">
<span class="text-sm font-medium">Verknüpft mit</span>
<UBadge
v-for="link in links"
:key="link.id"
color="primary"
variant="soft"
class="gap-1"
>
{{ link.entityTypeLabel }}: {{ link.entityName }}
<button
type="button"
class="ml-1 rounded hover:text-error"
:disabled="saving"
:aria-label="`Verknüpfung mit ${link.entityName} entfernen`"
@click="removeLink(link)"
>
<UIcon name="i-heroicons-x-mark" class="size-3.5" />
</button>
</UBadge>
<span v-if="!links.length" class="text-sm text-dimmed">Noch keine Zuordnung</span>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<USelectMenu
v-model="selectedEntityType"
:items="entityTypes"
value-key="value"
label-key="label"
size="sm"
class="w-36"
/>
<USelectMenu
v-model="selectedEntityId"
:items="entityOptions"
value-key="value"
label-key="label"
size="sm"
class="min-w-64 flex-1"
placeholder="Entität auswählen"
:loading="loadingOptions"
/>
<UButton
icon="i-heroicons-link"
size="sm"
:loading="saving"
:disabled="!selectedEntityId"
@click="addLink"
>
Verknüpfen
</UButton>
</div>
</div>
</template>

View File

@@ -0,0 +1,129 @@
<script setup lang="ts">
type EmailAddress = {
name?: string | null
address?: string | null
}
type LinkedMessage = {
id: string
accountId: string
mailboxPath: string
subject?: string | null
from?: EmailAddress[] | null
to?: EmailAddress[] | null
preview?: string | null
receivedAt?: string | null
sentAt?: string | null
linkedAt: string
hasAttachments: boolean
canOpen: boolean
}
const props = defineProps<{
entityType: string
entityId: string | number
}>()
const messages = ref<LinkedMessage[]>([])
const loading = ref(true)
const errorMessage = ref("")
const formatAddress = (addresses?: EmailAddress[] | null) => {
const address = addresses?.[0]
if (!address) return "Unbekannt"
return address.name || address.address || "Unbekannt"
}
const formatDate = (value?: string | null) => {
if (!value) return ""
return new Intl.DateTimeFormat("de-DE", {
dateStyle: "medium",
timeStyle: "short",
}).format(new Date(value))
}
const openMessage = (message: LinkedMessage) => navigateTo({
path: "/email",
query: {
account: message.accountId,
mailbox: message.mailboxPath,
message: message.id,
},
})
async function loadMessages() {
loading.value = true
errorMessage.value = ""
try {
messages.value = await useNuxtApp().$api(
`/api/email/entity-links/${props.entityType}/${props.entityId}`,
)
} catch (err: any) {
errorMessage.value = err?.data?.error || err?.message || "Verknüpfte E-Mails konnten nicht geladen werden."
} finally {
loading.value = false
}
}
watch(() => [props.entityType, props.entityId], loadMessages, { immediate: true })
</script>
<template>
<div class="space-y-3">
<div v-if="loading" class="space-y-3">
<USkeleton v-for="index in 4" :key="index" class="h-28" />
</div>
<UAlert
v-else-if="errorMessage"
color="error"
icon="i-heroicons-exclamation-triangle"
title="E-Mails konnten nicht geladen werden"
:description="errorMessage"
/>
<TableEmptyState
v-else-if="!messages.length"
label="Noch keine E-Mails mit dieser Entität verknüpft"
/>
<article
v-for="message in messages"
v-else
:key="message.id"
class="rounded-lg border border-(--ui-border) bg-(--ui-bg) p-4"
>
<div class="flex items-start justify-between gap-4">
<div class="min-w-0">
<h3 class="truncate font-medium text-highlighted">
{{ message.subject || '(kein Betreff)' }}
</h3>
<p class="mt-1 text-sm text-dimmed">
Von {{ formatAddress(message.from) }} · {{ formatDate(message.receivedAt || message.sentAt) }}
</p>
</div>
<UButton
v-if="message.canOpen"
icon="i-heroicons-arrow-top-right-on-square"
color="neutral"
variant="soft"
size="sm"
@click="openMessage(message)"
>
Im Postfach öffnen
</UButton>
</div>
<p class="mt-3 line-clamp-2 text-sm text-muted">
{{ message.preview || 'Keine Vorschau verfügbar' }}
</p>
<div class="mt-3 flex items-center gap-3 text-xs text-dimmed">
<span>Verknüpft am {{ formatDate(message.linkedAt) }}</span>
<span v-if="message.hasAttachments" class="flex items-center gap-1">
<UIcon name="i-heroicons-paper-clip" class="size-3.5" />
Anhänge
</span>
</div>
</article>
</div>
</template>

View File

@@ -52,9 +52,17 @@ type EmailMessage = {
contentType?: string | null
size?: number | null
}>
entityLinks?: Array<{
id: string
entityType: string
entityId: number
entityName: string
entityTypeLabel: string
}>
}
const { $api } = useNuxtApp()
const route = useRoute()
const runtimeConfig = useRuntimeConfig()
const toast = useToast()
@@ -74,6 +82,7 @@ const expandedMailboxPaths = ref<string[]>([])
const syncedMailboxPaths = ref<string[]>([])
const actionLoading = ref("")
const moveTargetMailboxPath = ref("")
let deepLinkApplied = false
const selectedAccount = computed(() =>
accounts.value.find((account) => account.id === selectedAccountId.value) || null
@@ -295,7 +304,10 @@ async function loadAccounts() {
loadingAccounts.value = true
try {
accounts.value = await $api("/api/email/accounts")
selectedAccountId.value = accounts.value[0]?.id || ""
const requestedAccountId = String(route.query.account || "")
selectedAccountId.value = accounts.value.some((account) => account.id === requestedAccountId)
? requestedAccountId
: accounts.value[0]?.id || ""
if (selectedAccountId.value) {
await loadMailboxes()
}
@@ -316,7 +328,9 @@ async function loadMailboxes() {
resetExpandedMailboxes()
const inbox = mailboxes.value.find((mailbox) => mailbox.specialUse === "\\Inbox" || mailbox.path.toUpperCase() === "INBOX")
const previousMailbox = mailboxes.value.find((mailbox) => mailbox.path === previousMailboxPath)
selectedMailboxPath.value = previousMailbox?.path || inbox?.path || mailboxes.value[0]?.path || "INBOX"
const requestedMailboxPath = String(route.query.mailbox || "")
const requestedMailbox = mailboxes.value.find((mailbox) => mailbox.path === requestedMailboxPath)
selectedMailboxPath.value = requestedMailbox?.path || previousMailbox?.path || inbox?.path || mailboxes.value[0]?.path || "INBOX"
expandMailboxAncestors(selectedMailboxPath.value)
await loadMessages()
} finally {
@@ -340,7 +354,10 @@ async function loadMessages(options: { syncIfEmpty?: boolean } = {}) {
}
if (messages.value.length) {
await selectMessage(messages.value[0])
const requestedMessageId = deepLinkApplied ? "" : String(route.query.message || "")
const requestedMessage = messages.value.find((message) => message.id === requestedMessageId)
await selectMessage(requestedMessage || messages.value[0])
deepLinkApplied = true
}
} finally {
loadingMessages.value = false
@@ -375,6 +392,22 @@ async function selectMessage(message: EmailMessage) {
}
}
function updateSelectedMessageEntityLinks(entityLinks: NonNullable<EmailMessage["entityLinks"]>) {
if (!selectedMessage.value) return
selectedMessage.value = { ...selectedMessage.value, entityLinks }
}
function openComposer(mode: "reply" | "replyAll" | "forward") {
if (!selectedMessage.value) return
navigateTo({
path: "/email/new",
query: {
mode,
source: selectedMessage.value.id,
},
})
}
function removeMessageFromCurrentList(messageId: string) {
const currentIndex = messages.value.findIndex((message) => message.id === messageId)
messages.value = messages.value.filter((message) => message.id !== messageId)
@@ -800,16 +833,26 @@ onMounted(loadAccounts)
color="neutral"
variant="soft"
size="sm"
@click="navigateTo(`/email/new?to=${encodeURIComponent(formatAddressList(selectedMessage.from))}&subject=${encodeURIComponent(`Re: ${selectedMessage.subject || ''}`)}`)"
@click="openComposer('reply')"
>
Antworten
</UButton>
<UButton
v-if="selectedMessage.cc?.length || (selectedMessage.to?.length || 0) > 1"
icon="i-heroicons-users"
color="neutral"
variant="ghost"
size="sm"
@click="openComposer('replyAll')"
>
Allen antworten
</UButton>
<UButton
icon="i-heroicons-arrow-uturn-right"
color="neutral"
variant="ghost"
size="sm"
@click="navigateTo(`/email/new?subject=${encodeURIComponent(`Fw: ${selectedMessage.subject || ''}`)}`)"
@click="openComposer('forward')"
>
Weiterleiten
</UButton>
@@ -831,6 +874,12 @@ onMounted(loadAccounts)
</p>
</div>
<EmailEntityLinks
:message-id="selectedMessage.id"
:entity-links="selectedMessage.entityLinks"
@updated="updateSelectedMessageEntityLinks"
/>
<div v-if="selectedMessage.attachments?.length" class="mt-4 flex flex-wrap gap-2">
<button
v-for="attachment in selectedMessage.attachments"

View File

@@ -21,6 +21,55 @@ const preloadedContent = ref("")
const loadedDocuments = ref([])
const loaded = ref(false)
const noAccountsPresent = ref(false)
const sourceMessage = ref(null)
const composeMode = computed(() => {
const mode = String(route.query.mode || "")
return ["reply", "replyAll", "forward"].includes(mode) ? mode : "new"
})
const pageTitle = computed(() => ({
reply: "Antworten",
replyAll: "Allen antworten",
forward: "E-Mail weiterleiten",
}[composeMode.value] || "Neue E-Mail"))
const escapeHtml = (value = "") => String(value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;")
const formatAddress = (address) => {
if (!address?.address) return ""
return address.name ? `"${String(address.name).replace(/"/g, "\\\"")}" <${address.address}>` : address.address
}
const formatAddressList = (addresses = []) => addresses.map(formatAddress).filter(Boolean).join(", ")
const prefixedSubject = (prefix, subject = "") => {
const cleanSubject = String(subject || "")
return cleanSubject.toLowerCase().startsWith(prefix.toLowerCase()) ? cleanSubject : `${prefix} ${cleanSubject}`.trim()
}
const originalMessageBlock = (message, mode) => {
const sentAt = message.sentAt || message.receivedAt
const date = sentAt ? new Intl.DateTimeFormat("de-DE", {
dateStyle: "full",
timeStyle: "short",
}).format(new Date(sentAt)) : ""
const originalText = escapeHtml(message.body?.text || message.preview || "").replace(/\n/g, "<br>")
if (mode === "forward") {
return `<hr><p><strong>Weitergeleitete Nachricht</strong><br>`
+ `Von: ${escapeHtml(formatAddressList(message.from))}<br>`
+ `Datum: ${escapeHtml(date)}<br>`
+ `Betreff: ${escapeHtml(message.subject || "(kein Betreff)")}<br>`
+ `An: ${escapeHtml(formatAddressList(message.to))}</p><blockquote>${originalText}</blockquote>`
}
return `<hr><blockquote><p>Am ${escapeHtml(date)} schrieb ${escapeHtml(formatAddressList(message.from))}:</p>${originalText}</blockquote>`
}
const setupPage = async () => {
//emailAccounts.value = await useEntities("emailAccounts").select()
@@ -31,7 +80,41 @@ const setupPage = async () => {
} else {
emailData.value.account = emailAccounts.value[0].id
preloadedContent.value = `<p></p><p></p><p></p>${auth.profile.email_signature || ""}`
let initialContent = `<p></p><p></p><p></p>${auth.profile.email_signature || ""}`
if (route.query.source && composeMode.value !== "new") {
sourceMessage.value = await useNuxtApp().$api(`/api/email/messages/${route.query.source}`)
const sourceAccount = emailAccounts.value.find(account => account.id === sourceMessage.value.accountId)
if (sourceAccount) emailData.value.account = sourceAccount.id
if (composeMode.value === "forward") {
emailData.value.subject = prefixedSubject("Fw:", sourceMessage.value.subject)
} else {
const ownAddress = String(sourceAccount?.email || "").toLowerCase()
const replyRecipients = sourceMessage.value.replyTo?.length
? sourceMessage.value.replyTo
: sourceMessage.value.from || []
if (composeMode.value === "replyAll") {
const allRecipients = [
...replyRecipients,
...(sourceMessage.value.to || []),
...(sourceMessage.value.cc || []),
].filter(address => address?.address && address.address.toLowerCase() !== ownAddress)
const uniqueRecipients = Array.from(new Map(
allRecipients.map(address => [address.address.toLowerCase(), address])
).values())
emailData.value.to = formatAddressList(uniqueRecipients)
} else {
emailData.value.to = formatAddressList(replyRecipients)
}
emailData.value.subject = prefixedSubject("Re:", sourceMessage.value.subject)
}
initialContent += originalMessageBlock(sourceMessage.value, composeMode.value)
}
preloadedContent.value = initialContent
//Check Query
if(route.query.to) emailData.value.to = route.query.to
@@ -120,7 +203,9 @@ const sendEmail = async () => {
let body = {
...emailData.value,
attachments: []
attachments: [],
sourceMessageId: sourceMessage.value?.id,
composeMode: composeMode.value === "new" ? undefined : composeMode.value,
}
@@ -151,26 +236,28 @@ const sendEmail = async () => {
})
}
console.log(body)
try {
const res = await useNuxtApp().$api("/api/email/send",{
method: "POST",
body: body,
})
const res = await useNuxtApp().$api("/api/email/send",{
method: "POST",
body: body,
})
console.log(res)
if(!res.success) {
toast.add({title: "Fehler beim Absenden der E-Mail", color: "error"})
} else {
navigateTo("/")
toast.add({title: "E-Mail zum Senden eingereiht"})
if(!res.success) {
toast.add({title: "Fehler beim Absenden der E-Mail", color: "error"})
} else {
await navigateTo("/email")
toast.add({title: "E-Mail gesendet", color: "success"})
}
} catch (err) {
toast.add({
title: "Fehler beim Absenden der E-Mail",
description: err?.data?.error || err?.message,
color: "error",
})
} finally {
loaded.value = true
}
loaded.value = true
}
@@ -192,7 +279,7 @@ const sendEmail = async () => {
<div v-else>
<UDashboardNavbar
title="Neue E-Mail"
:title="pageTitle"
>
<template #right>
<UButton
@@ -280,6 +367,12 @@ const sendEmail = async () => {
>
<span v-if="doc.createddocument">Dokument - {{doc.createddocument.documentNumber}}</span>
</li>
<li
v-if="composeMode === 'forward' && sourceMessage?.attachments?.length"
class="list-disc"
>
{{ sourceMessage.attachments.length }} Originalanhang/Originalanhänge werden übernommen
</li>
</ul>
</div>

View File

@@ -494,7 +494,7 @@ export const useDataStore = defineStore('data', () => {
inputColumn: "Allgemeines"
},*/
],
showTabs: [{label: 'Informationen'},{label: 'Ansprechpartner'},{label: 'Dateien'},{label: 'Ausgangsbelege'},{label: 'Projekte'},{label: 'Objekte'},{label: 'Termine'},{label: 'Verträge'},{label: 'Ausgehende SEPA-Mandate', key: 'outgoingsepamandates', type: 'outgoingsepamandates'},{label: 'Kundeninventar', key: 'customerinventoryitems'},{label: 'Kundenlagerplätze', key: 'customerspaces'},{label: 'Wiki'}]
showTabs: [{label: 'Informationen'},{label: 'Ansprechpartner'},{label: 'E-Mails'},{label: 'Dateien'},{label: 'Ausgangsbelege'},{label: 'Projekte'},{label: 'Objekte'},{label: 'Termine'},{label: 'Verträge'},{label: 'Ausgehende SEPA-Mandate', key: 'outgoingsepamandates', type: 'outgoingsepamandates'},{label: 'Kundeninventar', key: 'customerinventoryitems'},{label: 'Kundenlagerplätze', key: 'customerspaces'},{label: 'Wiki'}]
},
members: {
isArchivable: true,
@@ -1463,6 +1463,8 @@ export const useDataStore = defineStore('data', () => {
label: "Projekte"
},{
label: "Aufgaben"
},{
label: "E-Mails"
},{
label: "Dateien"
},{
@@ -1741,6 +1743,8 @@ export const useDataStore = defineStore('data', () => {
},{
key: "tasks",
label: "Aufgaben"
},{
label: "E-Mails"
},{
key: "files",
label: "Dateien"
@@ -2024,6 +2028,8 @@ export const useDataStore = defineStore('data', () => {
label: 'Informationen',
},{
label: 'Ansprechpartner',
}, {
label: 'E-Mails',
}, {
label: 'Dateien',
}, {