Add EOI automation system with email processing and document management

- Implement automated EOI processing from sales emails
- Add EOI document upload and management capabilities
- Enhance email thread handling with better parsing and grouping
- Add retry logic and error handling for file operations
- Introduce Documeso integration for document processing
- Create server tasks and plugins infrastructure
- Update email composer with improved attachment handling
This commit is contained in:
2025-06-10 13:59:09 +02:00
parent 5c30411c2b
commit 218705da52
25 changed files with 2351 additions and 71 deletions

View File

@@ -0,0 +1,425 @@
<template>
<div>
<v-card-title class="text-h6 d-flex align-center pb-4">
<v-icon class="mr-2" color="primary">mdi-email</v-icon>
Email Communication
</v-card-title>
<v-card-text class="pt-0">
<!-- Compose New Email -->
<div class="mb-4">
<v-btn
@click="showComposer = true"
color="primary"
variant="flat"
prepend-icon="mdi-email-edit"
>
Compose Email
</v-btn>
</div>
<!-- Email Thread List -->
<div v-if="emailThreads.length > 0" class="email-threads">
<div class="text-subtitle-1 mb-3">Email History</div>
<v-timeline side="end" density="comfortable">
<v-timeline-item
v-for="(email, index) in emailThreads"
:key="index"
:dot-color="email.direction === 'sent' ? 'primary' : 'success'"
:icon="email.direction === 'sent' ? 'mdi-email-send' : 'mdi-email-receive'"
size="small"
>
<template v-slot:opposite>
<div class="text-caption">
{{ formatDate(email.timestamp) }}
</div>
</template>
<v-card variant="outlined">
<v-card-subtitle class="d-flex align-center">
<span class="text-body-2">
{{ email.direction === 'sent' ? 'To' : 'From' }}:
{{ email.direction === 'sent' ? email.to : email.from }}
</span>
</v-card-subtitle>
<v-card-text>
<div class="text-body-2 font-weight-medium mb-2">{{ email.subject }}</div>
<div class="email-content" v-html="formatEmailContent(email.content)"></div>
<!-- Attachments -->
<div v-if="email.attachments && email.attachments.length > 0" class="mt-3">
<v-chip
v-for="(attachment, i) in email.attachments"
:key="i"
size="small"
color="primary"
variant="tonal"
prepend-icon="mdi-paperclip"
class="mr-2"
>
{{ attachment.name }}
</v-chip>
</div>
</v-card-text>
</v-card>
</v-timeline-item>
</v-timeline>
</div>
<!-- Empty State -->
<div v-else class="text-center py-8 text-grey">
<v-icon size="48" class="mb-3">mdi-email-outline</v-icon>
<div>No email communication yet</div>
</div>
</v-card-text>
<!-- Email Composer Dialog -->
<v-dialog v-model="showComposer" max-width="800" persistent>
<v-card>
<v-card-title class="d-flex align-center">
<v-icon class="mr-2">mdi-email-edit</v-icon>
Compose Email
<v-spacer />
<v-btn icon="mdi-close" variant="text" @click="closeComposer"></v-btn>
</v-card-title>
<v-divider />
<v-card-text>
<!-- Recipient Info -->
<v-alert type="info" variant="tonal" class="mb-4">
<div class="d-flex align-center">
<v-icon class="mr-2">mdi-account</v-icon>
<div>
<div class="font-weight-medium">{{ interest['Full Name'] }}</div>
<div class="text-caption">{{ interest['Email Address'] }}</div>
</div>
</div>
</v-alert>
<!-- Subject -->
<v-text-field
v-model="emailDraft.subject"
label="Subject"
variant="outlined"
density="comfortable"
class="mb-4"
/>
<!-- Quick Actions -->
<div class="mb-3">
<span class="text-body-2 mr-2">Quick Insert:</span>
<v-btn
v-if="hasEOI"
@click="insertEOILink"
size="small"
variant="tonal"
prepend-icon="mdi-file-document"
>
EOI Link
</v-btn>
<v-btn
@click="insertFormLink"
size="small"
variant="tonal"
prepend-icon="mdi-form-select"
class="ml-2"
>
Interest Form
</v-btn>
<v-btn
v-if="hasBerth"
@click="insertBerthInfo"
size="small"
variant="tonal"
prepend-icon="mdi-anchor"
class="ml-2"
>
Berth Info
</v-btn>
</div>
<!-- Email Content -->
<v-textarea
v-model="emailDraft.content"
label="Email Content"
variant="outlined"
rows="12"
placeholder="Write your email here..."
ref="contentTextarea"
/>
<!-- Attachments -->
<v-file-input
v-model="emailDraft.attachments"
label="Attachments"
variant="outlined"
density="comfortable"
multiple
chips
prepend-icon="mdi-paperclip"
class="mt-4"
/>
</v-card-text>
<v-divider />
<v-card-actions>
<v-spacer />
<v-btn @click="closeComposer" variant="text">Cancel</v-btn>
<v-btn
@click="sendEmail"
color="primary"
variant="flat"
prepend-icon="mdi-send"
:loading="isSending"
>
Send Email
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script setup lang="ts">
import type { Interest } from '~/utils/types';
const props = defineProps<{
interest: Interest;
}>();
const emit = defineEmits<{
'email-sent': [];
'update': [];
}>();
const toast = useToast();
const showComposer = ref(false);
const isSending = ref(false);
const emailThreads = ref<any[]>([]);
const contentTextarea = ref<any>(null);
const emailDraft = ref<{
subject: string;
content: string;
attachments: File[];
}>({
subject: '',
content: '',
attachments: []
});
// Check if interest has EOI or berth
const hasEOI = computed(() => {
const eoiDocs = props.interest['EOI Document'];
const hasEOIDocs = Array.isArray(eoiDocs) && eoiDocs.length > 0;
return !!(props.interest['Signature Link Client'] || hasEOIDocs);
});
const hasBerth = computed(() => {
const berths = props.interest.Berths;
const hasBerthsArray = Array.isArray(berths) && berths.length > 0;
return !!(hasBerthsArray || props.interest['Berth Number']);
});
// Load email thread on mount
onMounted(() => {
loadEmailThread();
});
// Watch for interest changes
watch(() => props.interest.Id, () => {
loadEmailThread();
});
const loadEmailThread = async () => {
try {
const response = await $fetch<{
success: boolean;
emails: any[];
}>('/api/email/fetch-thread', {
method: 'POST',
headers: {
'x-tag': '094ut234'
},
body: {
email: props.interest['Email Address']
}
});
if (response.success) {
emailThreads.value = response.emails || [];
}
} catch (error) {
console.error('Failed to load email thread:', error);
}
};
const insertEOILink = () => {
if (!contentTextarea.value) return;
const link = props.interest['Signature Link Client'] ||
props.interest['EOI Client Link'] ||
'EOI document has been generated for your review';
const insertText = `\n\nPlease review and sign your Expression of Interest (EOI) document:\n${link}\n\n`;
insertAtCursor(insertText);
};
const insertFormLink = () => {
const formLink = `https://form.portnimara.com/interest/${props.interest.Id}`;
const insertText = `\n\nPlease complete your interest form:\n${formLink}\n\n`;
insertAtCursor(insertText);
};
const insertBerthInfo = () => {
let berthNumber = props.interest['Berth Number'];
// Check if Berths is an array and has items
if (!berthNumber && Array.isArray(props.interest.Berths) && props.interest.Berths.length > 0) {
berthNumber = props.interest.Berths[0]['Berth Number'];
}
const insertText = `\n\nBerth Information:\nBerth Number: ${berthNumber || 'TBD'}\n\n`;
insertAtCursor(insertText);
};
const insertAtCursor = (text: string) => {
const textarea = contentTextarea.value.$el.querySelector('textarea');
if (!textarea) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const current = emailDraft.value.content;
emailDraft.value.content = current.substring(0, start) + text + current.substring(end);
// Set cursor position after inserted text
nextTick(() => {
textarea.focus();
textarea.setSelectionRange(start + text.length, start + text.length);
});
};
const sendEmail = async () => {
if (!emailDraft.value.subject || !emailDraft.value.content) {
toast.error('Please enter a subject and message');
return;
}
isSending.value = true;
try {
// Format email content with proper line breaks
const formattedContent = emailDraft.value.content
.split('\n')
.map(line => line.trim() ? `<p>${line}</p>` : '<br>')
.join('');
// Prepare email data
const emailData = {
to: props.interest['Email Address'],
toName: props.interest['Full Name'],
subject: emailDraft.value.subject,
html: formattedContent,
interestId: props.interest.Id.toString()
};
// Send email
const response = await $fetch<{
success: boolean;
messageId?: string;
}>('/api/email/send', {
method: 'POST',
headers: {
'x-tag': '094ut234'
},
body: emailData
});
if (response.success) {
toast.success('Email sent successfully');
// Add to thread
emailThreads.value.unshift({
direction: 'sent',
to: props.interest['Email Address'],
subject: emailDraft.value.subject,
content: formattedContent,
timestamp: new Date().toISOString(),
attachments: emailDraft.value.attachments.map((f: File) => ({ name: f.name }))
});
// Close composer and reset
closeComposer();
emit('email-sent');
emit('update');
}
} catch (error: any) {
console.error('Failed to send email:', error);
toast.error(error.data?.statusMessage || 'Failed to send email');
} finally {
isSending.value = false;
}
};
const closeComposer = () => {
showComposer.value = false;
// Reset draft
emailDraft.value = {
subject: '',
content: '',
attachments: []
};
};
const formatDate = (dateString: string) => {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleString('en-GB', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
const formatEmailContent = (content: string) => {
// Ensure HTML content is properly formatted
if (content.includes('<p>') || content.includes('<br>')) {
return content;
}
// Convert plain text to HTML
return content.split('\n').map(line => `<p>${line}</p>`).join('');
};
</script>
<style scoped>
.email-content {
max-height: 200px;
overflow-y: auto;
line-height: 1.6;
}
.email-content :deep(p) {
margin: 0 0 0.5em 0;
}
.email-content :deep(br) {
display: block;
content: "";
margin: 0.5em 0;
}
.email-threads {
max-height: 600px;
overflow-y: auto;
}
</style>

View File

@@ -5,9 +5,31 @@
EOI Management
</v-card-title>
<v-card-text class="pt-0">
<!-- Generate EOI Button -->
<div v-if="!hasEOI" class="mb-4">
<!-- EOI Documents Section -->
<div v-if="hasEOIDocuments" class="mb-4">
<div class="text-subtitle-1 mb-2">EOI Documents</div>
<div class="d-flex flex-wrap ga-2">
<v-chip
v-for="(doc, index) in eoiDocuments"
:key="index"
color="primary"
variant="tonal"
prepend-icon="mdi-file-pdf-box"
:href="doc.url"
target="_blank"
component="a"
clickable
closable
@click:close="removeDocument(index)"
>
{{ doc.title || `EOI Document ${index + 1}` }}
</v-chip>
</div>
</div>
<!-- Generate EOI Button - Only show if no documents uploaded -->
<div v-if="!hasEOI && !hasEOIDocuments" class="mb-4">
<v-btn
@click="generateEOI"
:loading="isGenerating"
@@ -18,6 +40,18 @@
Generate EOI
</v-btn>
</div>
<!-- Upload EOI Button -->
<div class="mb-4">
<v-btn
@click="showUploadDialog = true"
variant="outlined"
prepend-icon="mdi-upload"
:disabled="isUploading"
>
{{ hasEOI ? 'Upload Signed EOI' : 'Upload EOI Document' }}
</v-btn>
</div>
<!-- EOI Status Badge -->
<div v-if="hasEOI" class="mb-4 d-flex align-center">
@@ -100,6 +134,37 @@
</v-btn>
</div>
</v-card-text>
<!-- Upload Dialog -->
<v-dialog v-model="showUploadDialog" max-width="500">
<v-card>
<v-card-title>Upload EOI Document</v-card-title>
<v-card-text>
<v-file-input
v-model="selectedFile"
label="Select EOI document (PDF)"
accept=".pdf"
prepend-icon="mdi-file-pdf-box"
variant="outlined"
density="comfortable"
:rules="[v => !!v || 'Please select a file']"
/>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn @click="showUploadDialog = false">Cancel</v-btn>
<v-btn
color="primary"
variant="flat"
@click="handleUpload"
:loading="isUploading"
:disabled="!selectedFile"
>
Upload
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
@@ -115,8 +180,11 @@ const emit = defineEmits<{
'update': [];
}>();
const { showToast } = useToast();
const toast = useToast();
const isGenerating = ref(false);
const showUploadDialog = ref(false);
const isUploading = ref(false);
const selectedFile = ref<File | null>(null);
const hasEOI = computed(() => {
return !!(props.interest['Signature Link Client'] ||
@@ -124,7 +192,15 @@ const hasEOI = computed(() => {
props.interest['Signature Link Developer']);
});
const generateEOI = async () => {
const eoiDocuments = computed(() => {
return props.interest['EOI Document'] || [];
});
const hasEOIDocuments = computed(() => {
return eoiDocuments.value.length > 0;
});
const generateEOI = async (retryCount = 0) => {
isGenerating.value = true;
try {
@@ -144,16 +220,27 @@ const generateEOI = async () => {
});
if (response.success) {
showToast(response.documentId === 'existing'
toast.success(response.documentId === 'existing'
? 'EOI already exists - signature links retrieved'
: 'EOI generated successfully');
emit('eoi-generated', { signingLinks: response.signingLinks });
emit('update'); // Trigger parent to refresh data
} else {
throw new Error('EOI generation failed');
}
} catch (error: any) {
console.error('Failed to generate EOI:', error);
showToast(error.data?.statusMessage || 'Failed to generate EOI');
// Retry logic
if (retryCount < 3) {
console.log(`Retrying EOI generation... Attempt ${retryCount + 2}/4`);
await new Promise(resolve => setTimeout(resolve, (retryCount + 1) * 1000));
return generateEOI(retryCount + 1);
}
// Show error message after all retries failed
toast.error(error.data?.statusMessage || error.message || 'Failed to generate EOI after multiple attempts');
} finally {
isGenerating.value = false;
}
@@ -164,7 +251,7 @@ const copyLink = async (link: string | undefined) => {
try {
await navigator.clipboard.writeText(link);
showToast('Signature link copied to clipboard');
toast.success('Signature link copied to clipboard');
// Update EOI Time Sent if not already set
if (!props.interest['EOI Time Sent']) {
@@ -187,7 +274,7 @@ const copyLink = async (link: string | undefined) => {
}
}
} catch (error) {
showToast('Failed to copy link');
toast.error('Failed to copy link');
}
};
@@ -225,4 +312,45 @@ const getStatusColor = (status: string) => {
return 'grey';
}
};
const removeDocument = async (index: number) => {
// For now, we'll just show a message since removing documents
// would require updating the database
toast.warning('Document removal is not yet implemented');
};
const uploadEOI = async (file: File) => {
isUploading.value = true;
try {
const formData = new FormData();
formData.append('file', file);
const response = await $fetch<{ success: boolean; document: any; message: string }>('/api/eoi/upload-document', {
method: 'POST',
query: {
interestId: props.interest.Id.toString()
},
body: formData
});
if (response.success) {
toast.success('EOI document uploaded successfully');
showUploadDialog.value = false;
selectedFile.value = null; // Reset file selection
emit('update'); // Refresh parent data
}
} catch (error: any) {
console.error('Failed to upload EOI:', error);
toast.error(error.data?.statusMessage || 'Failed to upload EOI document');
} finally {
isUploading.value = false;
}
};
const handleUpload = () => {
if (selectedFile.value) {
uploadEOI(selectedFile.value);
}
};
</script>

View File

@@ -184,14 +184,12 @@
</v-btn>
</v-toolbar>
<v-card-text class="pa-0">
<div style="height: 600px; overflow: hidden;">
<file-browser-component
v-if="showFileBrowser"
:selection-mode="true"
@file-selected="onFileSelected"
/>
</div>
<v-card-text class="pa-0" style="height: 70vh; overflow-y: auto;">
<file-browser-component
v-if="showFileBrowser"
:selection-mode="true"
@file-selected="onFileSelected"
/>
</v-card-text>
<v-divider />

View File

@@ -131,7 +131,6 @@
v-if="interest['EOI Time Sent']"
color="warning"
variant="tonal"
prepend-icon="mdi-email-fast"
>
EOI Sent: {{ formatDate(interest["EOI Time Sent"]) }}
</v-chip>
@@ -624,10 +623,11 @@
</v-card>
<!-- Email Communication Section -->
<EmailCommunication
<ClientEmailSection
v-if="interest"
:interest="interest"
@interestUpdated="onInterestUpdated"
@email-sent="onInterestUpdated"
@update="onInterestUpdated"
/>
</v-form>
</v-card-text>
@@ -658,7 +658,7 @@ function debounce<T extends (...args: any[]) => any>(
return debounced;
}
import PhoneInput from "./PhoneInput.vue";
import EmailCommunication from "./EmailCommunication.vue";
import ClientEmailSection from "./ClientEmailSection.vue";
import EOISection from "./EOISection.vue";
import {
InterestSalesProcessLevelFlow,