import fs from 'node:fs'; import { createHash } from 'node:crypto'; import axios from 'axios'; import { PDFDocument } from 'pdf-lib'; import { cloudServerUrl, replaceMailVaribles, saveFileUsage, getSecureUrl, serverAppId, } from '../../../Utils.js'; import { escapeHtml, renderDocumentEmail, resolveBrandContext, resolveDeploymentBrand, } from '../../../utils/brandContext.js'; import GenerateCertificate from './GenerateCertificate.js'; import { pdflibAddPlaceholder } from '@signpdf/placeholder-pdf-lib'; import { Placeholder } from './Placeholder.js'; import { SignPdf } from '@signpdf/signpdf'; import { P12Signer } from '@signpdf/signer-p12'; import { buildDownloadFilename, parseUploadFile } from '../../../utils/fileUtils.js'; import sendMailWithAttachment from '../sendMailWithAttachment.js'; import sendSystemMail from '../sendSystemMail.js'; import { COMPLETION_ACTIVITIES, findPlaceholderIndex, findPendingPriorSigner, isCompletionRelevant, } from '../../../utils/workflowUtils.js'; // Audit-trail activities that count toward document completion. The free // build only counts 'Signed'; EE additionally counts 'Approved'. // A placeholder participates in completion unless it is a prefill entry. // EE additionally excludes viewers (who never act on the document). // Strict-order gating: returns the signerObjId of the prior placeholder // still pending, or null when the strict-order requirement is satisfied. const serverUrl = cloudServerUrl; // process.env.SERVER_URL; const APPID = serverAppId; const masterKEY = process.env.MASTER_KEY; const deploymentBrand = resolveDeploymentBrand(); const eSignName = deploymentBrand.digitalSignature.name; const eSigncontact = deploymentBrand.digitalSignature.contact; const docUrl = `${serverUrl}/classes/contracts_Document`; const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY, }; function generateDocumentHash(buffer) { return createHash('sha256').update(buffer).digest('hex'); } async function unlinkFile(path) { if (fs.existsSync(path)) { try { fs.unlinkSync(path); } catch (err) { console.log('Err in unlink file: ', path); } } } // `updateDoc` is used to create url in from pdfFile async function uploadFile(pdfName, filepath) { try { const filedata = fs.readFileSync(filepath); let fileUrl; const fileRes = await parseUploadFile(pdfName, filedata, 'application/pdf'); fileUrl = getSecureUrl(fileRes?.url)?.url; return { imageUrl: fileUrl }; } catch (err) { console.log('Err ', err); // below line of code is used to remove exported signed pdf file from exports folder unlinkFile(filepath); } } // `updateDoc` is used to update signedUrl, AuditTrail, Iscompleted in document async function updateDoc( docId, url, userId, ipAddress, data, className, sign, documentHash, activity ) { try { const UserPtr = { __type: 'Pointer', className: className, objectId: userId }; const auditActivity = 'Signed'; const obj = { UserPtr: UserPtr, SignedUrl: url, Activity: auditActivity, ipAddress: ipAddress, SignedOn: new Date(), Signature: sign, }; let updateAuditTrail; if (data.AuditTrail && data.AuditTrail.length > 0) { const AuditTrail = JSON.parse(JSON.stringify(data.AuditTrail)); const existingIndex = AuditTrail.findIndex( entry => entry.UserPtr.objectId === userId && entry.Activity !== 'Created' ); existingIndex !== -1 ? (AuditTrail[existingIndex] = { ...AuditTrail[existingIndex], ...obj }) : AuditTrail.push(obj); updateAuditTrail = AuditTrail; } else { updateAuditTrail = [obj]; } // Count both Signed and Approved entries; only signer/approver // placeholders count toward completion (viewers and prefill excluded). const auditTrail = updateAuditTrail.filter(x => COMPLETION_ACTIVITIES.includes(x.Activity)); let isCompleted = false; if (data.Signers && data.Signers.length > 0) { const completionRelevant = data.Placeholders?.length > 0 ? data.Placeholders.filter(isCompletionRelevant) : []; if (auditTrail.length >= completionRelevant.length && completionRelevant.length > 0) { isCompleted = true; } } else { isCompleted = true; } const body = { SignedUrl: url, AuditTrail: updateAuditTrail, IsCompleted: isCompleted }; if (documentHash && isCompleted) { body.DocumentHash = documentHash; } const signedRes = await axios.put(`${docUrl}/${docId}`, body, { headers }); return { isCompleted: isCompleted, message: 'success', AuditTrail: updateAuditTrail, DocumentHash: documentHash && isCompleted ? documentHash : undefined, }; } catch (err) { console.log('update doc err ', err); return 'err'; } } // `sendNotifyMail` is used to send notification mail of signer signed the document async function sendNotifyMail(doc, signUser, mailProvider, publicUrl) { try { const brand = resolveBrandContext({}); const auditTrailCount = doc?.AuditTrail?.filter(x => COMPLETION_ACTIVITIES.includes(x.Activity))?.length || 0; const completionRelevant = doc?.Placeholders?.length > 0 ? doc.Placeholders.filter(isCompletionRelevant) : []; const signersCount = completionRelevant?.length; const remainingSign = signersCount - auditTrailCount; if (remainingSign > 1 && doc?.NotifyOnSignatures) { const sender = doc.ExtUserPtr; const pdfName = doc.Name; const creatorName = doc.ExtUserPtr.Name; const creatorEmail = doc.ExtUserPtr.Email; const signerName = signUser.Name; const signerEmail = signUser.Email; const viewDocUrl = `${publicUrl}/recipientSignPdf/${doc.objectId}`; const subject = `Document "${pdfName}" has been signed by ${signerName}`; const body = renderDocumentEmail({ context: brand, heading: `Document signed by ${signerName}`, contentHtml: `
Dear ${escapeHtml(creatorName)},
${escapeHtml(pdfName)} has been signed by ${escapeHtml(signerName)} "${escapeHtml(signerEmail)}" successfully
` + `All parties have successfully signed the document "${escapeHtml(pdfName)}". Kindly download the document from the attachment.
`, senderEmail: sender.Email, }); if (obj?.isCustomMail) { const tenant = sender?.TenantId; if (tenant) { subject = tenant?.CompletionSubject ? tenant?.CompletionSubject : subject; body = tenant?.CompletionBody ? tenant?.CompletionBody : body; } else { const userId = sender?.CreatedBy?.objectId || sender?.UserId?.objectId; if (userId) { try { const tenantQuery = new Parse.Query('partners_Tenant'); tenantQuery.equalTo('UserId', { __type: 'Pointer', className: '_User', objectId: userId, }); const tenantRes = await tenantQuery.first({ useMasterKey: true }); if (tenantRes) { const _tenantRes = JSON.parse(JSON.stringify(tenantRes)); subject = _tenantRes?.CompletionSubject ? tenant?.CompletionSubject : subject; body = _tenantRes?.CompletionBody ? tenant?.CompletionBody : body; } } catch (err) { console.log('error in fetch tenant in signpdf', err.message); } } } const expireDate = doc.ExpiryDate.iso; const newDate = new Date(expireDate); const localExpireDate = newDate.toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric', }); const variables = { document_title: pdfName, note: doc?.Note, sender_name: doc?.SenderName || sender.Name, sender_mail: doc?.SenderMail || sender.Email, sender_phone: sender?.Phone || '', receiver_name: sender.Name, receiver_email: sender.Email, receiver_phone: sender?.Phone || '', expiry_date: localExpireDate, company_name: sender.Company, }; const replaceVar = replaceMailVaribles(subject, body, variables); subject = replaceVar.subject; body = replaceVar.body; } const Bcc = doc?.Bcc?.length > 0 ? doc.Bcc.map(x => x.Email) : []; const Cc = doc?.Cc?.length > 0 ? doc.Cc.map(x => x.Email) : []; const updatedBcc = doc?.SenderMail ? [...Bcc, doc?.SenderMail] : Bcc; const formatId = doc?.ExtUserPtr?.DownloadFilenameFormat; const filename = pdfName?.length > 100 ? pdfName?.slice(0, 100) : pdfName; const docName = buildDownloadFilename(formatId, { docName: filename, email: doc?.ExtUserPtr?.Email, isSigned: true, }); const params = { extUserId: sender.objectId, url: url, from: doc?.SenderName || brand.senderName, replyto: doc?.SenderMail || doc?.ExtUserPtr?.Email || '', recipient: recipient, subject: subject, pdfName: pdfName, html: body, mailProvider: obj.mailProvider, bcc: updatedBcc?.length > 0 ? updatedBcc : '', cc: Cc?.length > 0 ? Cc : '', certificatePath: `./exports/signed_certificate_${doc.objectId}.pdf`, filename: docName, }; try { const res = await sendMailWithAttachment(params); // console.log("res ", res) if (res?.status !== 'success') { unlinkFile(`./exports/signed_certificate_${doc.objectId}.pdf`); } } catch (err) { unlinkFile(`./exports/signed_certificate_${doc.objectId}.pdf`); } } // `sendMailsaveCertifcate` is used send completion mail and update complete status of document async function sendMailsaveCertifcate(doc, pfx, isCustomMail, mailProvider, filename) { const certificate = await GenerateCertificate(doc); const certificatePdf = await PDFDocument.load(certificate); const P12Buffer = fs.readFileSync(pfx.name); const p12 = new P12Signer(P12Buffer, { passphrase: pfx.passphrase || null }); // `pdflibAddPlaceholder` is used to add code of only digitial sign in certificate pdflibAddPlaceholder({ pdfDoc: certificatePdf, reason: `Digitally signed by ${eSignName}.`, location: 'n/a', name: eSignName, contactInfo: eSigncontact, signatureLength: 16000, }); const pdfWithPlaceholderBytes = await certificatePdf.save(); const CertificateBuffer = Buffer.from(pdfWithPlaceholderBytes); //`new signPDF` create new instance of CertificateBuffer and p12Buffer const certificateOBJ = new SignPdf(); // `signedCertificate` is used to sign certificate digitally const signedCertificate = await certificateOBJ.sign(CertificateBuffer, p12); const certificatePath = `./exports/signed_certificate_${doc.objectId}.pdf`; //below is used to save signed certificate in exports folder fs.writeFileSync(certificatePath, signedCertificate); const file = await uploadFile('certificate.pdf', certificatePath); const body = { CertificateUrl: file.imageUrl }; await axios.put(`${docUrl}/${doc.objectId}`, body, { headers }); // used in API only if (doc.IsSendMail === false) { console.log("don't send mail"); } else { sendCompletedMail({ isCustomMail, doc, mailProvider, filename }); } saveFileUsage(CertificateBuffer.length, file.imageUrl, doc?.CreatedBy?.objectId); unlinkFile(pfx.name); return file.imageUrl; } /** * Process a PDF for signing: * - updates audit trail, generates certificate. * - Optionally inserts a signature placeholder (Placeholder()). * - Otherwise (no merge + no placeholder), it flattens forms for finalization. * * @param {Object} _resDoc - Document details (expects AuditTrail, etc.) * @param {Buffer|Uint8Array} pdfBytes - Original PDF bytes * @param {string} [options.reason] - Reason text used in placeholder * @param {string} [options.UserPtr] - user pointer (for audit trail) * @param {string} [options.ipAddress] - IP (for audit trail) * @param {string} [options.Signature] - Signature (for audit trail) * @returns {Promise