This commit is contained in:
2025-06-11 14:08:28 +02:00
parent 0b6601fabc
commit f992fbb5a6
6 changed files with 717 additions and 85 deletions

View File

@@ -43,6 +43,27 @@ export default defineEventHandler(async (event) => {
throw createError({ statusCode: 404, statusMessage: "Interest not found" });
}
// Documenso API configuration - moved to top for use throughout
const documensoApiKey = process.env.NUXT_DOCUMENSO_API_KEY;
const documensoBaseUrl = process.env.NUXT_DOCUMENSO_BASE_URL;
const templateId = '9';
if (!documensoApiKey || !documensoBaseUrl) {
throw createError({
statusCode: 500,
statusMessage: "Documenso configuration missing. Please check NUXT_DOCUMENSO_API_KEY and NUXT_DOCUMENSO_BASE_URL environment variables."
});
}
// Check if uploaded EOI documents exist - prevent generation if they do
const eoiDocuments = interest['EOI Document'] || [];
if (eoiDocuments.length > 0) {
throw createError({
statusCode: 400,
statusMessage: "Cannot generate EOI - uploaded documents already exist. Please remove uploaded documents first."
});
}
// Check if EOI already exists (has signature links)
if (interest['Signature Link Client'] && interest['Signature Link CC'] && interest['Signature Link Developer']) {
console.log('EOI already exists, returning existing links');
@@ -58,6 +79,29 @@ export default defineEventHandler(async (event) => {
};
}
// If there's an existing generated document, delete it from Documenso first
if (interest['documensoID']) {
console.log('Existing generated document found, deleting from Documenso first');
try {
const deleteResponse = await fetch(`${documensoBaseUrl}/api/v1/documents/${interest['documensoID']}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${documensoApiKey}`,
'Content-Type': 'application/json'
}
});
if (deleteResponse.ok) {
console.log('Successfully deleted old document from Documenso');
} else {
console.warn('Failed to delete old document from Documenso, continuing with new generation');
}
} catch (error) {
console.warn('Error deleting old document from Documenso:', error);
// Continue with generation even if deletion fails
}
}
// Validate required fields
const requiredFields = [
{ field: 'Full Name', value: interest['Full Name'] },
@@ -104,18 +148,6 @@ export default defineEventHandler(async (event) => {
// Concatenate berth numbers
const berthNumbers = berths.map(b => b['Mooring Number']).join(', ');
// Documenso API configuration
const documensoApiKey = process.env.NUXT_DOCUMENSO_API_KEY;
const documensoBaseUrl = process.env.NUXT_DOCUMENSO_BASE_URL;
const templateId = '9';
if (!documensoApiKey || !documensoBaseUrl) {
throw createError({
statusCode: 500,
statusMessage: "Documenso configuration missing. Please check NUXT_DOCUMENSO_API_KEY and NUXT_DOCUMENSO_BASE_URL environment variables."
});
}
// 1. Get template (optional - just to verify it exists)
try {
const templateResponse = await fetch(`${documensoBaseUrl}/api/v1/templates/${templateId}`, {
@@ -272,7 +304,8 @@ export default defineEventHandler(async (event) => {
'EOI Status': 'Waiting for Signatures',
'Sales Process Level': 'LOI and NDA Sent',
// Don't set EOI Time Sent here - only when email is sent or link is copied
'Extra Comments': updatedComments
'Extra Comments': updatedComments,
'documensoID': documentResponse.documentId.toString()
};
// Add signing links to update data with new column names

View File

@@ -64,6 +64,7 @@ export default defineEventHandler(async (event) => {
'Signature Link CC': null,
'Signature Link Developer': null,
'Documeso ID': null,
'documensoID': null,
'reminder_enabled': false
};

View File

@@ -0,0 +1,131 @@
import { getInterestById, updateInterest } from '~/server/utils/nocodb';
import { checkDocumentSignatureStatus } from '~/server/utils/documeso';
import type { InterestSalesProcessLevel, EOIStatus } from '~/utils/types';
export default defineEventHandler(async (event) => {
const xTagHeader = getRequestHeader(event, "x-tag");
console.log('[Delete Generated EOI] Request received with x-tag:', xTagHeader);
if (!xTagHeader || (xTagHeader !== "094ut234" && xTagHeader !== "pjnvü1230")) {
console.error('[Delete Generated EOI] Authentication failed - invalid x-tag');
throw createError({ statusCode: 401, statusMessage: "unauthenticated" });
}
try {
const body = await readBody(event);
const { interestId } = body;
console.log('[Delete Generated EOI] Interest ID:', interestId);
if (!interestId) {
console.error('[Delete Generated EOI] No interest ID provided');
throw createError({
statusCode: 400,
statusMessage: 'Interest ID is required',
});
}
// Get current interest data
const interest = await getInterestById(interestId);
if (!interest) {
throw createError({
statusCode: 404,
statusMessage: 'Interest not found',
});
}
const documensoID = interest['documensoID'];
console.log('[Delete Generated EOI] Documenso ID:', documensoID);
if (!documensoID) {
throw createError({
statusCode: 400,
statusMessage: 'No generated document found to delete',
});
}
// Check if document is fully signed - prevent deletion if it is
try {
const signatureStatus = await checkDocumentSignatureStatus(parseInt(documensoID));
console.log('[Delete Generated EOI] Signature status:', signatureStatus);
if (signatureStatus.allSigned) {
throw createError({
statusCode: 400,
statusMessage: 'Cannot delete a fully signed document. All parties have already signed.',
});
}
} catch (error: any) {
console.error('[Delete Generated EOI] Failed to check signature status:', error);
// If we can't check status, we'll proceed with deletion but warn
console.warn('[Delete Generated EOI] Proceeding with deletion despite signature status check failure');
}
// Delete document from Documenso
const documensoApiKey = process.env.NUXT_DOCUMENSO_API_KEY;
const documensoBaseUrl = process.env.NUXT_DOCUMENSO_BASE_URL;
if (!documensoApiKey || !documensoBaseUrl) {
throw createError({
statusCode: 500,
statusMessage: "Documenso configuration missing. Please check NUXT_DOCUMENSO_API_KEY and NUXT_DOCUMENSO_BASE_URL environment variables."
});
}
console.log('[Delete Generated EOI] Deleting document from Documenso');
try {
const deleteResponse = await fetch(`${documensoBaseUrl}/api/v1/documents/${documensoID}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${documensoApiKey}`,
'Content-Type': 'application/json'
}
});
if (!deleteResponse.ok) {
const errorText = await deleteResponse.text();
console.error('[Delete Generated EOI] Documenso deletion failed:', errorText);
throw new Error(`Failed to delete document from Documenso: ${deleteResponse.statusText}`);
}
console.log('[Delete Generated EOI] Successfully deleted document from Documenso');
} catch (error: any) {
console.error('[Delete Generated EOI] Documenso deletion error:', error);
throw createError({
statusCode: 500,
statusMessage: `Failed to delete document from Documenso: ${error.message}`,
});
}
// Reset interest fields
const updateData = {
'EOI Status': 'Awaiting Further Details' as EOIStatus,
'Sales Process Level': 'Specific Qualified Interest' as InterestSalesProcessLevel,
'EOI Time Sent': undefined,
'Signature Link Client': undefined,
'Signature Link CC': undefined,
'Signature Link Developer': undefined,
'documensoID': undefined,
'reminder_enabled': false
};
console.log('[Delete Generated EOI] Resetting interest fields');
// Update the interest
await updateInterest(interestId, updateData);
console.log('[Delete Generated EOI] Delete completed successfully');
return {
success: true,
message: 'Generated EOI document deleted successfully',
};
} catch (error: any) {
console.error('[Delete Generated EOI] Failed to delete generated EOI document:', error);
console.error('[Delete Generated EOI] Error stack:', error.stack);
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.statusMessage || error.message || 'Failed to delete generated EOI document',
});
}
});