feat: attach digital sign to completion certificate

This commit is contained in:
prafull-opensignlabs
2024-04-04 15:26:41 +05:30
parent ba839b0fc8
commit 6c16d00031
10 changed files with 535 additions and 524 deletions
@@ -5,9 +5,7 @@ async function DocumentBeforesave(request) {
const oldDocument = request.original;
// Check if SignedUrl field has been added (transition from undefined to defined)
if (!oldDocument.get('SignedUrl') && document.get('SignedUrl')) {
const SignedUrl = document.get('SignedUrl');
if (!oldDocument?.get('SignedUrl') && document?.get('SignedUrl')) {
// Update count in contracts_Users class
const query = new Parse.Query('contracts_Users');
query.equalTo('objectId', oldDocument.get('ExtUserPtr').id);
@@ -0,0 +1,244 @@
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
import fs from 'node:fs';
export default async function GenerateCertificate(docDetails) {
const pdfDoc = await PDFDocument.create();
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
const pngUrl = fs.readFileSync('./logo.png').buffer;
const pngImage = await pdfDoc.embedPng(pngUrl);
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
const startX = 15;
const startY = 15;
const borderColor = rgb(0.12, 0.12, 0.12);
const titleColor = rgb(0, 0.2, 0.4); //rgb(0, 0.53, 0.71);
const titleUnderline = rgb(0, 0.2, 0.4); // rgb(0.12, 0.12, 0.12);
const title = 25;
const subtitle = 20;
const text = 14;
const textKeyColor = rgb(0.12, 0.12, 0.12);
const textValueColor = rgb(0.3, 0.3, 0.3);
const completedAt = new Date(docDetails.updatedAt);
const completedUTCtime = completedAt.toUTCString();
const signersCount = docDetails?.Signers?.length || 1;
const createdAt = new Date();
const createdUTCTime = createdAt.toUTCString();
const createDate = 'Generated On ' + createdUTCTime;
const company = docDetails?.ExtUserPtr?.Company || '';
const auditTrail =
docDetails.AuditTrail?.length > 1
? docDetails.AuditTrail.map(x => {
const data = docDetails.Signers.find(y => y.objectId === x.UserPtr.objectId);
return { ...data, ipAddress: x.ipAddress };
})
: [{ ...docDetails.ExtUserPtr, ipAddress: docDetails?.AuditTrail[0].ipAddress }];
// Draw a border
page.drawRectangle({
x: startX,
y: startY,
width: width - 2 * startX,
height: height - 2 * startY,
borderColor: borderColor,
borderWidth: 1,
});
page.drawImage(pngImage, {
x: 30,
y: 790,
width: 100,
height: 25,
});
page.drawText(createDate, {
x: 320,
y: 810,
size: 12,
font: timesRomanFont,
color: rgb(0.12, 0.12, 0.12),
});
page.drawText('Certificate of Completion', {
x: 160,
y: 750,
size: title,
font: timesRomanFont,
color: titleColor,
});
const underlineY = 740;
page.drawLine({
start: { x: 30, y: underlineY },
end: { x: width - 30, y: underlineY },
color: titleUnderline,
thickness: 1,
});
page.drawText('Summary', {
x: 30,
y: 710,
size: subtitle,
font: timesRomanFont,
color: titleColor,
});
page.drawText('Document Id :', {
x: 30,
y: 685,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(docDetails.objectId, {
x: 115,
y: 685,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawText('Document Name :', {
x: 30,
y: 665,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(docDetails.Name, {
x: 140,
y: 665,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawText('Organization :', {
x: 30,
y: 645,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(company, {
x: 115,
y: 645,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawText('Completed on :', {
x: 30,
y: 625,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(`${completedUTCtime}`, {
x: 120,
y: 625,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawText('Signers :', {
x: 30,
y: 605,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(`${signersCount}`, {
x: 80,
y: 605,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawLine({
start: { x: 30, y: 565 },
end: { x: width - 30, y: 565 },
color: rgb(0.12, 0.12, 0.12),
thickness: 0.5,
});
page.drawText('Recipients', {
x: 30,
y: 575,
size: subtitle,
font: timesRomanFont,
color: titleColor,
});
let yPosition1 = 550;
let yPosition2 = 530;
let yPosition3 = 510;
let yPosition4 = 500;
auditTrail.forEach(x => {
page.drawText('Name :', {
x: 30,
y: yPosition1,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(x?.Name, {
x: 75,
y: yPosition1,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawText('Email :', {
x: 30,
y: yPosition2,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(x?.Email, {
x: 75,
y: yPosition2,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawText('Accessed from :', {
x: 30,
y: yPosition3,
size: text,
font: timesRomanFont,
color: textKeyColor,
});
page.drawText(x?.ipAddress, {
x: 125,
y: yPosition3,
size: text,
font: timesRomanFont,
color: textValueColor,
});
page.drawLine({
start: { x: 30, y: yPosition4 },
end: { x: width - 30, y: yPosition4 },
color: rgb(0.12, 0.12, 0.12),
thickness: 0.5,
});
yPosition1 = yPosition4 - 20;
yPosition2 = yPosition1 - 20;
yPosition3 = yPosition2 - 20;
yPosition4 = yPosition4 - 70;
});
const pdfBytes = await pdfDoc.save();
return pdfBytes;
}
+110 -74
View File
@@ -4,6 +4,7 @@ import axios from 'axios';
import { pdflibAddPlaceholder } from './customSignPdf/pdflibplaceholder.min.js';
import { PDFDocument } from 'pdf-lib';
import { saveFileUsage } from '../../../Utils.js';
import GenerateCertificate from './GenerateCertificate.js';
const serverUrl = process.env.SERVER_URL,
APPID = process.env.APP_ID,
masterKEY = process.env.MASTER_KEY;
@@ -17,20 +18,20 @@ async function uploadFile(e, a) {
console.log('Err ', e), fs.unlinkSync(a);
}
}
async function updateDoc(t, s, r, o, i, n) {
async function updateDoc(t, s, r, i, o, n) {
try {
var d = {
UserPtr: { __type: 'Pointer', className: n, objectId: r },
SignedUrl: s,
Activity: 'Signed',
ipAddress: o,
ipAddress: i,
};
let e;
var l = (e = i.AuditTrail && 0 < i.AuditTrail.length ? [...i.AuditTrail, d] : [d]).filter(
var l = (e = o.AuditTrail && 0 < o.AuditTrail.length ? [...o.AuditTrail, d] : [d]).filter(
e => 'Signed' === e.Activity
);
let a = !1;
!((i.Signers && 0 < i.Signers.length && l.length !== i.Signers.length) || !(a = !0));
!((o.Signers && 0 < o.Signers.length && l.length !== o.Signers.length) || !(a = !0));
var c = { SignedUrl: s, AuditTrail: e, IsCompleted: a };
await axios.put(serverUrl + '/classes/contracts_Document/' + t, c, {
headers: {
@@ -39,7 +40,7 @@ async function updateDoc(t, s, r, o, i, n) {
'X-Parse-Master-Key': masterKEY,
},
});
return { isCompleted: a, message: 'success' };
return { isCompleted: a, message: 'success', AuditTrail: e };
} catch (e) {
return console.log('update doc err ', e), 'err';
}
@@ -129,12 +130,12 @@ async function sendDoctoWebhook(t, e, a, s) {
}
}));
}
async function PDF(i) {
async function PDF(o) {
try {
var e = i.params.docId,
a = i.params.userId,
n = await axios.get(
serverUrl + '/classes/contracts_Document/' + e + '?include=ExtUserPtr,Signers',
var n = o.params.docId,
e = o.params.userId,
d = await axios.get(
serverUrl + '/classes/contracts_Document/' + n + '?include=ExtUserPtr,Signers',
{
headers: {
'Content-Type': 'application/json',
@@ -143,66 +144,66 @@ async function PDF(i) {
},
}
),
d = await axios.get(serverUrl + '/users/me', {
l = await axios.get(serverUrl + '/users/me', {
headers: {
'X-Parse-Application-Id': APPID,
'X-Parse-Session-Token': i.headers.sessiontoken,
'X-Parse-Session-Token': o.headers.sessiontoken,
},
});
if (!d.data || !d.data.objectId) return { status: 'error', message: 'This user not allowed!' };
if (!l.data || !l.data.objectId) return { status: 'error', message: 'This user not allowed!' };
{
var t,
var a,
t,
s,
l,
c = JSON.stringify({ objectId: a });
let r, o;
o = a
? (t = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + c, {
c = JSON.stringify({ objectId: e });
let r, i;
i = e
? (a = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + c, {
headers: {
'X-Parse-Application-Id': APPID,
'X-Parse-Session-Token': i.headers.sessiontoken,
'X-Parse-Session-Token': o.headers.sessiontoken,
},
})).data && 0 < t.data.results.length
? ((r = t), 'contracts_Contactbook')
})).data && 0 < a.data.results.length
? ((r = a), 'contracts_Contactbook')
: ((r = await axios.get(serverUrl + '/classes/contracts_Users?where=' + c, {
headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY },
})),
'contracts_Users')
: ((s = JSON.stringify({
UserId: { __type: 'Pointer', className: '_User', objectId: d.data.objectId },
: ((t = JSON.stringify({
UserId: { __type: 'Pointer', className: '_User', objectId: l.data.objectId },
})),
(l = await axios.get(serverUrl + '/classes/contracts_Users?where=' + s, {
(s = await axios.get(serverUrl + '/classes/contracts_Users?where=' + t, {
headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY },
})).data && 0 < l.data.results.length
? ((r = l), 'contracts_Users')
: ((r = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + s, {
})).data && 0 < s.data.results.length
? ((r = s), 'contracts_Users')
: ((r = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + t, {
headers: {
'X-Parse-Application-Id': APPID,
'X-Parse-Session-Token': i.headers.sessiontoken,
'X-Parse-Session-Token': o.headers.sessiontoken,
},
})),
'contracts_Contactbook'));
var p = r.data.results[0].Name,
m = r.data.results[0].Email;
if (!i.params.pdfFile) return { status: 'error', message: 'pdf file not present!' };
if (!o.params.pdfFile) return { status: 'error', message: 'Pdf file not present!' };
{
let e = Buffer.from(i.params.pdfFile, 'base64');
let e = Buffer.from(o.params.pdfFile, 'base64');
var g = process.env.PFX_BASE64,
u = Buffer.from(g, 'base64'),
h = {
UserPtr: { __type: 'Pointer', className: o, objectId: r.data.results[0].objectId },
f = {
UserPtr: { __type: 'Pointer', className: i, objectId: r.data.results[0].objectId },
SignedUrl: '',
Activity: 'Signed',
ipAddress: i.headers['x-real-ip'],
ipAddress: o.headers['x-real-ip'],
};
let a;
var f = (a =
n.data.AuditTrail && 0 < n.data.AuditTrail.length
? [...n.data.AuditTrail, h]
: [h]).filter(e => 'Signed' === e.Activity);
var h = (a =
d.data.AuditTrail && 0 < d.data.AuditTrail.length
? [...d.data.AuditTrail, f]
: [f]).filter(e => 'Signed' === e.Activity);
let t = !1;
!(
(n.data.Signers && 0 < n.data.Signers.length && f.length !== n.data.Signers.length) ||
(d.data.Signers && 0 < d.data.Signers.length && h.length !== d.data.Signers.length) ||
!(t = !0)
);
var P,
@@ -211,19 +212,19 @@ async function PDF(i) {
U,
b,
I,
S = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`,
x = './exports/' + S;
w = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`,
A = './exports/' + w;
let s = e.length;
s = (
t
? ((P = n.data.Signers?.map(e => e.Name + ' <' + e.Email + '>')),
? ((P = d.data.Signers?.map(e => e.Name + ' <' + e.Email + '>')),
(e =
P && 0 < P.length
? ((y = await PDFDocument.load(e)),
pdflibAddPlaceholder({
pdfDoc: y,
reason: 'Digitally signed by OpenSign for ' + P?.join(', '),
location: 'location',
location: 'n/a',
signatureLength: 15e3,
}),
(v = await y.save()),
@@ -232,49 +233,84 @@ async function PDF(i) {
pdflibAddPlaceholder({
pdfDoc: U,
reason: 'Digitally signed by OpenSign for ' + p + ' <' + m + '>',
location: 'location',
location: 'n/a',
signatureLength: 15e3,
}),
(b = await U.save()),
Buffer.from(b))),
(I = await new SignPDF(e, u).signPDF()),
fs.writeFileSync(x, I),
fs.writeFileSync(A, I),
I)
: (fs.writeFileSync(x, e), e)
: (fs.writeFileSync(A, e), e)
).length;
var A,
w,
D = await uploadFile(S, x);
if (D && D.imageUrl)
var D,
S,
x,
E,
_,
j,
k,
F,
T,
N,
C = await uploadFile(w, A);
if (C && C.imageUrl)
return (
(A = await updateDoc(
i.params.docId,
D.imageUrl,
(D = await updateDoc(
o.params.docId,
C.imageUrl,
r.data.results[0].objectId,
i.headers['x-real-ip'],
n.data,
o
o.headers['x-real-ip'],
d.data,
i
)),
sendDoctoWebhook(n, D.imageUrl, 'signed', r?.data.results?.[0]),
saveFileUsage(s, D.imageUrl, d.data.objectId),
A &&
A.isCompleted &&
((w = {
url: D.imageUrl,
sender: { Mail: n.data.ExtUserPtr.Email, Name: 'OpenSign™' },
pdfName: n.data.Name,
receiver: n.data.ExtUserPtr.Email,
extUserId: n.data.ExtUserPtr.objectId,
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,
}),
n.data.IsSendMail && !1 === n.data.IsSendMail
(x = { ...d.data, AuditTrail: D.AuditTrail }),
(E = await GenerateCertificate(x)),
(_ = await PDFDocument.load(E)),
pdflibAddPlaceholder({
pdfDoc: _,
reason: 'Digitally signed by OpenSign.',
location: 'n/a',
signatureLength: 15e3,
}),
(j = await _.save()),
(k = Buffer.from(j)),
(F = await new SignPDF(k, u).signPDF()),
fs.writeFileSync('./exports/certificate.pdf', F),
(N = {
CertificateUrl: (T = await uploadFile(
'certificate.pdf',
'./exports/certificate.pdf'
)).imageUrl,
}),
await axios.put(serverUrl + '/classes/contracts_Document/' + n, N, {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': APPID,
'X-Parse-Master-Key': masterKEY,
},
}),
d.data.IsSendMail && !1 === d.data.IsSendMail
? console.log("don't send mail")
: sendCompletedMail(w),
sendDoctoWebhook(n, D.imageUrl, 'completed')),
fs.unlinkSync(x),
console.log('New Signed PDF created called: ' + x),
'success' === A.message
? { status: 'success', data: D.imageUrl }
: { status: 'error', message: 'please provide required parameters!' }
: 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 }
: { status: 'error', message: 'Please provide required parameters!' }
);
}
}
@@ -58,8 +58,20 @@ async function sendmailv3(req) {
data: process.env.SMTP_ENABLE ? undefined : PdfBuffer,
};
// const html = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body style='text-align: center;'> <p style='font-weight: bolder; font-size: large;'>Hello!</p> <p>This is a html checking mail</p><p><button style='background-color: lightskyblue; cursor: pointer; border-radius: 5px; padding: 10px; border-style: solid; border-width: 2px; text-decoration: none; font-weight: bolder; color:blue'>Verify email</button></p></body></html>"
let attachment;
// `certificateBuffer` used to create buffer from pdf file
try {
const certificateBuffer = fs.readFileSync('./exports/certificate.pdf');
const certificate = {
filename: 'certificate.pdf',
content: process.env.SMTP_ENABLE ? certificateBuffer : undefined, //fs.readFileSync('./exports/exported_file_1223.pdf'),
data: process.env.SMTP_ENABLE ? undefined : certificateBuffer,
};
attachment = [file, certificate];
} catch (err) {
attachment = [file];
console.log('Err in read certificate sendmailv3', err);
}
const from = req.params.from || '';
const mailsender = process.env.SMTP_ENABLE
? process.env.SMTP_USER_EMAIL
@@ -71,8 +83,8 @@ async function sendmailv3(req) {
subject: req.params.subject,
text: req.params.text || 'mail',
html: req.params.html || '',
attachments: process.env.SMTP_ENABLE ? [file] : undefined,
attachment: process.env.SMTP_ENABLE ? undefined : file,
attachments: process.env.SMTP_ENABLE ? attachment : undefined,
attachment: process.env.SMTP_ENABLE ? undefined : attachment,
};
if (transporterSMTP) {
const res = await transporterSMTP.sendMail(messageParams);
@@ -81,6 +93,11 @@ async function sendmailv3(req) {
if (req.params?.extUserId) {
await updateMailCount(req.params.extUserId);
}
try {
fs.unlinkSync('./exports/certificate.pdf');
} catch (err) {
console.log('Err in unlink certificate sendmailv3');
}
return {
status: 'success',
};
@@ -92,6 +109,11 @@ async function sendmailv3(req) {
if (req.params?.extUserId) {
await updateMailCount(req.params.extUserId);
}
try {
fs.unlinkSync('./exports/certificate.pdf');
} catch (err) {
console.log('Err in unlink certificate sendmailv3');
}
return {
status: 'success',
};