🔥 The free & Open Source DocuSign alternative
JavaScript digital-signaturedocument-signingdocusign-alternativedocusign-freee-signatureelectronic-signatureelectronic-signaturesesignesignaturehacktoberfestjavascriptlegaltechmongodbnodejsopen-sourcepdf-signpdf-signaturereactjsself-hostedsign-pdf-files
feat: send custom completion mail if available
prafull-opensignlabs3c0db9473c75
diff --git a/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.min.js b/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.min.jsindex 0a8630125..5f73f8c62 100644--- a/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.min.js+++ b/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.min.js@@ -3,7 +3,7 @@ import fs from 'node:fs';import axios from 'axios';import { pdflibAddPlaceholder } from './customSignPdf/pdflibplaceholder.min.js';import { PDFDocument } from 'pdf-lib';-import { saveFileUsage } from '../../../Utils.js';+import { replaceMailVaribles, saveFileUsage } from '../../../Utils.js';import GenerateCertificate from './GenerateCertificate.js';const serverUrl = process.env.SERVER_URL,APPID = process.env.APP_ID,@@ -20,18 +20,18 @@ async function uploadFile(e, a) {}async function updateDoc(t, s, r, i, o, n) {try {- var d = {+ var l = {UserPtr: { __type: 'Pointer', className: n, objectId: r },SignedUrl: s,Activity: 'Signed',ipAddress: i,};let e;- var l = (e = o.AuditTrail && 0 < o.AuditTrail.length ? [...o.AuditTrail, d] : [d]).filter(+ var d = (e = o.AuditTrail && 0 < o.AuditTrail.length ? [...o.AuditTrail, l] : [l]).filter(e => 'Signed' === e.Activity);let a = !1;- !((o.Signers && 0 < o.Signers.length && l.length !== o.Signers.length) || !(a = !0));+ !((o.Signers && 0 < o.Signers.length && d.length !== o.Signers.length) || !(a = !0));var c = { SignedUrl: s, AuditTrail: e, IsCompleted: a };await axios.put(serverUrl + '/classes/contracts_Document/' + t, c, {headers: {@@ -47,23 +47,62 @@ async function updateDoc(t, s, r, i, o, n) {}async function sendCompletedMail(e) {var a = e.url,- t = e.sender,- s = e.pdfName,- r = e.receiver,- e = {- extUserId: e.extUserId,- url: a,- from: 'OpenSign™',- recipient: r,- subject: `Document ${s} has been signed by all parties`,- pdfName: s,- html:- "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body> <div style='background-color:#f5f5f5;padding:20px'> <div style='box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;background-color:white;'> <div><img src=https://qikinnovation.ams3.digitaloceanspaces.com/logo.png height='50' style='padding:20px'/> </div><div style='padding:2px;font-family:system-ui; background-color: #47a3ad;'> <p style='font-size:20px;font-weight:400;color:white;padding-left:20px',> Document sign successfully</p></div><div><p style='padding:20px;font-family:system-ui;font-size:14px'>All parties have successfully signed the document" +- s +- '. Kindly download the document from the attachment.</p></div> </div><div><p>This is an automated email from OpenSign™. For any queries regarding this email, please contact the sender ' +- t.Mail +- ' directly. If you think this email is inappropriate or spam, you may file a complaint with OpenSign™ <a href=www.opensignlabs.com target=_blank>here</a>.</p></div></div></body></html>',- };+ t = e.doc,+ s = e.doc.ExtUserPtr,+ r = t.Name,+ i = s.Email;+ let o = `Document "${r}" has been signed by all parties`,+ n =+ "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body> <div style='background-color:#f5f5f5;padding:20px'> <div style='box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;background-color:white;'> <div><img src=https://qikinnovation.ams3.digitaloceanspaces.com/logo.png height='50' style='padding:20px'/> </div><div style='padding:2px;font-family:system-ui; background-color: #47a3ad;'> <p style='font-size:20px;font-weight:400;color:white;padding-left:20px',> Document signed successfully</p></div><div><p style='padding:20px;font-family:system-ui;font-size:14px'>All parties have successfully signed the document " ++ `<b>"${r}"</b>` ++ '. Kindly download the document from the attachment.</p></div> </div><div><p>This is an automated email from OpenSign™. For any queries regarding this email, please contact the sender ' ++ s.Email ++ ' directly. If you think this email is inappropriate or spam, you may file a complaint with OpenSign™ <a href=www.opensignlabs.com target=_blank>here</a>.</p></div></div></body></html>';+ if (e?.isCustomMail)+ try {+ var l,+ d,+ c,+ p,+ m,+ g = new Parse.Query('partners_Tenant');+ g.equalTo('UserId', { __type: 'Pointer', className: '_User', objectId: s.UserId.objectId });+ const u = await g.first();+ u &&+ ((l = JSON.parse(JSON.stringify(u)))?.CompletionSubject && (o = l?.CompletionSubject),+ l?.CompletionBody && (n = l?.CompletionBody),+ (d = t.ExpiryDate.iso),+ (c = new Date(d).toLocaleDateString('en-US', {+ day: 'numeric',+ month: 'long',+ year: 'numeric',+ })),+ (p = {+ document_title: r,+ sender_name: s.Name,+ sender_mail: s.Email,+ sender_phone: s.Phone,+ receiver_name: s.Name,+ receiver_email: s.Email,+ receiver_phone: s.Phone,+ expiry_date: c,+ company_name: s.Company,+ }),+ (m = replaceMailVaribles(o, n, p)),+ (o = m.subject),+ (n = m.body));+ } catch (e) {+ console.log('error in fetch tenant in signpdf', e.message);+ }+ e = {+ extUserId: s.objectId,+ url: a,+ from: 'OpenSign™',+ recipient: i,+ subject: o,+ pdfName: r,+ html: n,+ };await axios.post(serverUrl + '/functions/sendmailv3', e, {headers: {'Content-Type': 'application/json',@@ -134,6 +173,7 @@ async function PDF(o) {try {var n = o.params.docId,e = o.params.userId,+ l = o.params.isCustomCompletionMail,d = await axios.get(serverUrl + '/classes/contracts_Document/' + n + '?include=ExtUserPtr,Signers',{@@ -144,33 +184,33 @@ async function PDF(o) {},}),- l = await axios.get(serverUrl + '/users/me', {+ c = await axios.get(serverUrl + '/users/me', {headers: {'X-Parse-Application-Id': APPID,'X-Parse-Session-Token': o.headers.sessiontoken,},});- if (!l.data || !l.data.objectId) return { status: 'error', message: 'This user not allowed!' };+ if (!c.data || !c.data.objectId) return { status: 'error', message: 'This user not allowed!' };{var a,t,s,- c = JSON.stringify({ objectId: e });+ p = JSON.stringify({ objectId: e });let r, i;i = e- ? (a = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + c, {+ ? (a = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + p, {headers: {'X-Parse-Application-Id': APPID,'X-Parse-Session-Token': o.headers.sessiontoken,},})).data && 0 < a.data.results.length? ((r = a), 'contracts_Contactbook')- : ((r = await axios.get(serverUrl + '/classes/contracts_Users?where=' + c, {+ : ((r = await axios.get(serverUrl + '/classes/contracts_Users?where=' + p, {headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY },})),'contracts_Users'): ((t = JSON.stringify({- UserId: { __type: 'Pointer', className: '_User', objectId: l.data.objectId },+ UserId: { __type: 'Pointer', className: '_User', objectId: c.data.objectId },})),(s = await axios.get(serverUrl + '/classes/contracts_Users?where=' + t, {headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY },@@ -183,13 +223,13 @@ async function PDF(o) {},})),'contracts_Contactbook'));- var p = r.data.results[0].Name,- m = r.data.results[0].Email;+ var m = r.data.results[0].Name,+ g = r.data.results[0].Email;if (!o.params.pdfFile) return { status: 'error', message: 'Pdf file not present!' };{let e = Buffer.from(o.params.pdfFile, 'base64');- var g = process.env.PFX_BASE64,- u = Buffer.from(g, 'base64'),+ var u = process.env.PFX_BASE64,+ h = Buffer.from(u, 'base64'),f = {UserPtr: { __type: 'Pointer', className: i, objectId: r.data.results[0].objectId },SignedUrl: '',@@ -197,104 +237,96 @@ async function PDF(o) {ipAddress: o.headers['x-real-ip'],};let a;- var h = (a =+ var P = (a =d.data.AuditTrail && 0 < d.data.AuditTrail.length? [...d.data.AuditTrail, f]: [f]).filter(e => 'Signed' === e.Activity);let t = !1;!(- (d.data.Signers && 0 < d.data.Signers.length && h.length !== d.data.Signers.length) ||+ (d.data.Signers && 0 < d.data.Signers.length && P.length !== d.data.Signers.length) ||!(t = !0));- var P,- y,+ var y,+ b,v,U,- b,I,- w = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`,- A = './exports/' + w;+ w,+ D = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`,+ S = './exports/' + D;let s = e.length;s = (t- ? ((P = d.data.Signers?.map(e => e.Name + ' <' + e.Email + '>')),+ ? ((y = d.data.Signers?.map(e => e.Name + ' <' + e.Email + '>')),(e =- P && 0 < P.length- ? ((y = await PDFDocument.load(e)),+ y && 0 < y.length+ ? ((b = await PDFDocument.load(e)),pdflibAddPlaceholder({- pdfDoc: y,- reason: 'Digitally signed by OpenSign for ' + P?.join(', '),+ pdfDoc: b,+ reason: 'Digitally signed by OpenSign for ' + y?.join(', '),location: 'n/a',signatureLength: 15e3,}),- (v = await y.save()),+ (v = await b.save()),Buffer.from(v)): ((U = await PDFDocument.load(e)),pdflibAddPlaceholder({pdfDoc: U,- reason: 'Digitally signed by OpenSign for ' + p + ' <' + m + '>',+ reason: 'Digitally signed by OpenSign for ' + m + ' <' + g + '>',location: 'n/a',signatureLength: 15e3,}),- (b = await U.save()),- Buffer.from(b))),- (I = await new SignPDF(e, u).signPDF()),- fs.writeFileSync(A, I),- I)- : (fs.writeFileSync(A, e), e)+ (I = await U.save()),+ Buffer.from(I))),+ (w = await new SignPDF(e, h).signPDF()),+ fs.writeFileSync(S, w),+ w)+ : (fs.writeFileSync(S, e), e)).length;- var D,- S,+ var _,+ A,x,E,- _,j,k,F,+ C,T,- N,- C = await uploadFile(w, A);- if (C && C.imageUrl)+ N = await uploadFile(D, S);+ if (N && N.imageUrl)return (- (D = await updateDoc(+ (_ = await updateDoc(o.params.docId,- C.imageUrl,+ N.imageUrl,r.data.results[0].objectId,o.headers['x-real-ip'],d.data,i)),- sendDoctoWebhook(d, C.imageUrl, 'signed', r?.data.results?.[0]),- saveFileUsage(s, C.imageUrl, l.data.objectId),- D &&- D.isCompleted &&- ((S = {- url: C.imageUrl,- sender: { Mail: d.data.ExtUserPtr.Email, Name: 'OpenSign™' },- pdfName: d.data.Name,- receiver: d.data.ExtUserPtr.Email,- extUserId: d.data.ExtUserPtr.objectId,- }),- (x = { ...d.data, AuditTrail: D.AuditTrail }),- (E = await GenerateCertificate(x)),- (_ = await PDFDocument.load(E)),+ sendDoctoWebhook(d, N.imageUrl, 'signed', r?.data.results?.[0]),+ saveFileUsage(s, N.imageUrl, c.data.objectId),+ _ &&+ _.isCompleted &&+ ((A = { ...d.data, AuditTrail: _.AuditTrail }),+ (x = await GenerateCertificate(A)),+ (E = await PDFDocument.load(x)),pdflibAddPlaceholder({- pdfDoc: _,+ pdfDoc: E,reason: 'Digitally signed by OpenSign.',location: 'n/a',signatureLength: 15e3,}),- (j = await _.save()),+ (j = await E.save()),(k = Buffer.from(j)),- (F = await new SignPDF(k, u).signPDF()),+ (F = await new SignPDF(k, h).signPDF()),fs.writeFileSync('./exports/certificate.pdf', F),- (N = {- CertificateUrl: (T = await uploadFile(+ (T = {+ CertificateUrl: (C = await uploadFile('certificate.pdf','./exports/certificate.pdf')).imageUrl,}),- await axios.put(serverUrl + '/classes/contracts_Document/' + n, N, {+ await axios.put(serverUrl + '/classes/contracts_Document/' + n, T, {headers: {'Content-Type': 'application/json','X-Parse-Application-Id': APPID,@@ -303,13 +335,13 @@ async function PDF(o) {}),d.data.IsSendMail && !1 === d.data.IsSendMail? console.log("don't send mail")- : sendCompletedMail(S),- saveFileUsage(k.length, T.imageUrl, l.data.objectId),- sendDoctoWebhook(d, C.imageUrl, 'completed')),- fs.unlinkSync(A),- console.log('New Signed PDF created called: ' + A),- 'success' === D.message- ? { status: 'success', data: C.imageUrl }+ : sendCompletedMail({ url: N.imageUrl, isCustomMail: l, doc: d.data }),+ saveFileUsage(k.length, C.imageUrl, c.data.objectId),+ sendDoctoWebhook(d, N.imageUrl, 'completed')),+ fs.unlinkSync(S),+ console.log('New Signed PDF created called: ' + S),+ 'success' === _.message+ ? { status: 'success', data: N.imageUrl }: { status: 'error', message: 'Please provide required parameters!' });}