Files
OpenSign/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.min.js
T

326 lines
11 KiB
JavaScript

import SignPDF from './SignPDF.min.cjs';
import fs from 'node:fs';
import axios from 'axios';
import { pdflibAddPlaceholder } from './customSignPdf/pdflibplaceholder.min.js';
import { PDFDocument } from 'pdf-lib';
import { replaceMailVaribles, 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;
async function uploadFile(e, t) {
try {
var a = fs.readFileSync(t),
r = new Parse.File(e, [...a], 'application/pdf'),
i = (await r.save({ useMasterKey: !0 }), r.url());
return { imageUrl: i };
} catch (e) {
console.log('Err ', e), fs.unlinkSync(t);
}
}
async function updateDoc(a, r, i, s, o, n, l) {
try {
var c,
d,
p = {
UserPtr: { __type: 'Pointer', className: n, objectId: i },
SignedUrl: r,
Activity: 'Signed',
ipAddress: s,
SignedOn: new Date(),
Signature: l,
};
let e;
var m = (e =
o.AuditTrail && 0 < o.AuditTrail.length
? (-1 !==
(d = (c = JSON.parse(JSON.stringify(o.AuditTrail))).findIndex(
e => e.UserPtr.objectId === i && 'Created' !== e.Activity
))
? (c[d] = { ...c[d], ...p })
: c.push(p),
c)
: [p]).filter(e => 'Signed' === e.Activity);
let t = !1;
!((o.Signers && 0 < o.Signers.length && m.length !== o.Signers.length) || !(t = !0));
var g = { SignedUrl: r, AuditTrail: e, IsCompleted: t };
await axios.put(serverUrl + '/classes/contracts_Document/' + a, g, {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': APPID,
'X-Parse-Master-Key': masterKEY,
},
});
return { isCompleted: t, message: 'success', AuditTrail: e };
} catch (e) {
return console.log('update doc err ', e), 'err';
}
}
async function sendCompletedMail(e) {
var t = e.url,
a = e.doc,
r = e.doc.ExtUserPtr,
i = a.Name,
s = r.Email;
let o = `Document "${i}" 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>"${i}"</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 ' +
r.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,
c,
d,
p,
m,
g = new Parse.Query('partners_Tenant');
g.equalTo('UserId', { __type: 'Pointer', className: '_User', objectId: r.UserId.objectId });
const f = await g.first();
f &&
((l = JSON.parse(JSON.stringify(f)))?.CompletionSubject && (o = l?.CompletionSubject),
l?.CompletionBody && (n = l?.CompletionBody),
(c = a.ExpiryDate.iso),
(d = new Date(c).toLocaleDateString('en-US', {
day: 'numeric',
month: 'long',
year: 'numeric',
})),
(p = {
document_title: i,
sender_name: r.Name,
sender_mail: r.Email,
sender_phone: r.Phone,
receiver_name: r.Name,
receiver_email: r.Email,
receiver_phone: r.Phone,
expiry_date: d,
company_name: r.Company,
}),
(m = replaceMailVaribles(o, n, p)),
(o = m.subject),
(n = m.body));
} catch (e) {
console.log('error in fetch tenant in signpdf', e.message);
}
g = {
extUserId: r.objectId,
url: t,
from: 'OpenSign™',
recipient: s,
subject: o,
pdfName: i,
html: n,
mailProvider: e.mailProvider,
};
await axios.post(serverUrl + '/functions/sendmailv3', g, {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': APPID,
'X-Parse-Master-Key': masterKEY,
},
});
}
async function sendDoctoWebhook(a, e, t, r) {
let i = [];
(i = r
? { name: r?.Name, email: r?.Email, phone: r?.Phone }
: a?.Signers?.map(e => ({ name: e.Name, email: e.Email, phone: e.Phone })) || [
{ name: a?.ExtUserPtr?.Name, email: a?.ExtUserPtr?.Email, phone: a?.ExtUserPtr?.Phone },
]),
a.ExtUserPtr?.Webhook &&
((r =
'signed' === t
? { signer: i, signedAt: new Date() }
: { signers: i, completedAt: new Date() }),
(t = {
event: t,
objectId: a?.objectId,
file: e || '',
name: a?.Name,
note: a?.Note || '',
description: a?.Description || '',
...r,
createdAt: a?.createdAt,
}),
axios
.post(a?.ExtUserPtr?.Webhook, t, { headers: { 'Content-Type': 'application/json' } })
.then(e => {
try {
var t = new Parse.Object('contracts_Webhook');
t.set('Log', e?.status),
t.set('UserId', {
__type: 'Pointer',
className: '_User',
objectId: a.ExtUserPtr.UserId.objectId,
}),
t.save(null, { useMasterKey: !0 });
} catch (e) {
console.log('err save in contracts_Webhook', e.message);
}
})
.catch(e => {
console.log('Err send data to webhook', e.message);
try {
var t = new Parse.Object('contracts_Webhook');
t.set('Log', e?.status),
t.set('UserId', {
__type: 'Pointer',
className: '_User',
objectId: a.ExtUserPtr.UserId.objectId,
}),
t.save(null, { useMasterKey: !0 });
} catch (e) {
console.log('err save in contracts_Webhook', e.message);
}
}));
}
const sendMailsaveCertifcate = async (e, t, a, r, i, s) => {
var o = await GenerateCertificate(e),
o = await PDFDocument.load(o),
o =
(pdflibAddPlaceholder({
pdfDoc: o,
reason: 'Digitally signed by OpenSign.',
location: 'n/a',
signatureLength: 15e3,
}),
await o.save()),
o = Buffer.from(o),
t = await new SignPDF(o, t).signPDF(),
t =
(fs.writeFileSync('./exports/certificate.pdf', t),
await uploadFile('certificate.pdf', './exports/certificate.pdf')),
n = { CertificateUrl: t.imageUrl };
await axios.put(serverUrl + '/classes/contracts_Document/' + e.objectId, n, {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': APPID,
'X-Parse-Master-Key': masterKEY,
},
}),
e.IsSendMail && !1 === e.IsSendMail
? console.log("don't send mail")
: sendCompletedMail({ url: a, isCustomMail: r, doc: e, mailProvider: i }),
saveFileUsage(o.length, t.imageUrl, s),
sendDoctoWebhook(e, a, 'completed');
};
async function PDF(o) {
try {
if (!o?.user)
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'User is not authenticated.');
{
var n = o?.user?.toJSON(),
e = o.params.docId;
const F = o.params.userId;
var l = o.params.isCustomCompletionMail || !1,
c = o.params.mailProvider || '',
d = o.params.signature || '',
t = new Parse.Query('contracts_Document'),
a =
(t.include('ExtUserPtr,Signers'),
t.equalTo('objectId', e),
await t.first({ useMasterKey: !0 }));
if (!a) throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Document not found.');
var r,
p = a?.toJSON();
let i, s;
F
? ((r = p.Signers.find(e => e.objectId === F)),
console.log('_contractUser ', r),
r && ((i = r), (s = 'contracts_Contactbook')))
: ((s = 'contracts_Users'), (i = p.ExtUserPtr));
var m,
g = i.Name,
f = i.Email;
if (!o.params.pdfFile) throw (((m = new Error('Pdf file not present!')).code = 400), m);
{
let e = Buffer.from(o.params.pdfFile, 'base64');
var u = process.env.PFX_BASE64,
h = Buffer.from(u, 'base64'),
y = {
UserPtr: { __type: 'Pointer', className: s, objectId: i.objectId },
SignedUrl: '',
Activity: 'Signed',
ipAddress: o.headers['x-real-ip'],
};
let t;
var P = (t = p.AuditTrail && 0 < p.AuditTrail.length ? [...p.AuditTrail, y] : [y]).filter(
e => 'Signed' === e.Activity
);
let a = !1;
!((p.Signers && 0 < p.Signers.length && P.length !== p.Signers.length) || !(a = !0));
var v,
b,
S,
w,
U,
D,
I = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`,
_ = './exports/' + I;
let r = e.length;
r = (
a
? ((v = p.Signers?.map(e => e.Name + ' <' + e.Email + '>')),
(e =
v && 0 < v.length
? ((b = await PDFDocument.load(e)),
pdflibAddPlaceholder({
pdfDoc: b,
reason: 'Digitally signed by OpenSign for ' + v?.join(', '),
location: 'n/a',
signatureLength: 15e3,
}),
(S = await b.save()),
Buffer.from(S))
: ((w = await PDFDocument.load(e)),
pdflibAddPlaceholder({
pdfDoc: w,
reason: 'Digitally signed by OpenSign for ' + g + ' <' + f + '>',
location: 'n/a',
signatureLength: 15e3,
}),
(U = await w.save()),
Buffer.from(U))),
(D = await new SignPDF(e, h).signPDF()),
fs.writeFileSync(_, D),
D)
: (fs.writeFileSync(_, e), e)
).length;
var E = await uploadFile(I, _);
if (E && E.imageUrl) {
var x,
A,
j = await updateDoc(
o.params.docId,
E.imageUrl,
i.objectId,
o.headers['x-real-ip'],
p,
s,
d
);
if (
(sendDoctoWebhook(p, E.imageUrl, 'signed', i),
saveFileUsage(r, E.imageUrl, n.objectId),
j &&
j.isCompleted &&
((x = { ...p, AuditTrail: j.AuditTrail }),
sendMailsaveCertifcate(x, h, E.imageUrl, l, c, n.objectId)),
fs.unlinkSync(_),
console.log('New Signed PDF created called: ' + _),
'success' === j.message)
)
return { status: 'success', data: E.imageUrl };
throw (((A = new Error('Please provide required parameters!')).code = 400), A);
}
}
}
} catch (e) {
throw (console.log('Err in signpdf', e), e);
}
}
export default PDF;