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 { saveFileUsage } from '../../../Utils.js'; const serverUrl = process.env.SERVER_URL, APPID = process.env.APP_ID, masterKEY = process.env.MASTER_KEY; async function uploadFile(e, a) { try { var t = fs.readFileSync(a), s = new Parse.File(e, [...t]), r = (await s.save({ useMasterKey: !0 }), s.url()); return { imageUrl: r }; } catch (e) { console.log('Err ', e), fs.unlinkSync(a); } } async function updateDoc(t, s, r, i, o, n) { try { var d = { 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( e => 'Signed' === e.Activity ); let a = !1; !((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: { 'Content-Type': 'application/json', 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY, }, }); return { isCompleted: a, message: 'success' }; } catch (e) { return console.log('update doc err ', e), 'err'; } } async function sendMail(e) { var a = e.url, t = e.sender, s = e.pdfName, a = { url: a, from: 'OpenSign™', recipient: e.receiver, subject: 'You have signed the doc - ' + s, pdfName: s, html: "

Document Copy

A copy of the document " + s + ' Standard is attached to this email. Kindly download the document from the attachment.

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™ here.

', }; await axios.post(serverUrl + '/functions/sendmailv3', a, { headers: { 'Content-Type': 'application/json', 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY, }, }); } async function sendCompletedMail(e) { var a = e.url, t = e.sender, s = e.pdfName, a = { url: a, from: 'OpenSign™', recipient: e.receiver, subject: `Document ${s} has been signed by all parties`, pdfName: s, html: "

Document sign successfully

All parties have successfully signed the document" + s + '. Kindly download the document from the attachment.

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™ here.

', }; await axios.post(serverUrl + '/functions/sendmailv3', a, { headers: { 'Content-Type': 'application/json', 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY, }, }); } async function sendDoctoWebhook(t, e, a, s) { let r = []; (r = s ? { name: s?.Name, email: s?.Email, phone: s?.Phone } : t?.data?.Signers?.map(e => ({ name: e.Name, email: e.Email, phone: e.Phone })) || [ { name: t?.data?.ExtUserPtr?.Name, email: t?.data?.ExtUserPtr?.Email, phone: t?.data?.ExtUserPtr?.Phone, }, ]), t.data.ExtUserPtr?.Webhook && ((s = 'signed' === a ? { signer: r, signedAt: new Date() } : { signers: r, completedAt: new Date() }), (a = { event: a, objectId: t?.data?.objectId, file: e || '', name: t?.data?.Name, note: t?.data?.Note || '', description: t?.data?.Description || '', ...s, createdAt: t?.data?.createdAt, }), await axios .post(t?.data?.ExtUserPtr?.Webhook, a, { headers: { 'Content-Type': 'application/json' } }) .then(e => { try { var a = new Parse.Object('contracts_Webhook'); a.set('Log', e?.status), a.set('UserId', { __type: 'Pointer', className: '_User', objectId: t.data.ExtUserPtr.UserId.objectId, }), a.save(null, { useMasterKey: !0 }); } catch (e) { console.log('err save in contracts_Webhook', e); } }) .catch(e => { console.log('Err send data to webhook', e); try { var a = new Parse.Object('contracts_Webhook'); a.set('Log', e?.status), a.set('UserId', { __type: 'Pointer', className: '_User', objectId: t.data.ExtUserPtr.UserId.objectId, }), a.save(null, { useMasterKey: !0 }); } catch (e) { console.log('err save in contracts_Webhook', e); } })); } async function PDF(o) { try { var e = o.params.docId, a = o.params.userId, n = await axios.get( serverUrl + '/classes/contracts_Document/' + e + '?include=ExtUserPtr,Signers', { headers: { 'Content-Type': 'application/json', 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY, }, } ), d = await axios.get(serverUrl + '/users/me', { headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Session-Token': o.headers.sessiontoken, }, }); if (!d.data || !d.data.objectId) return { status: 'error', message: 'This user not allowed!' }; { var t, s, l, c = JSON.stringify({ objectId: a }); let r, i; i = a ? (t = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + c, { headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Session-Token': o.headers.sessiontoken, }, })).data && 0 < t.data.results.length ? ((r = t), '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 }, })), (l = await axios.get(serverUrl + '/classes/contracts_Users?where=' + s, { 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, { headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Session-Token': o.headers.sessiontoken, }, })), 'contracts_Contactbook')); var p = r.data.results[0].Name, m = 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, h = Buffer.from(g, 'base64'), u = { UserPtr: { __type: 'Pointer', className: i, objectId: r.data.results[0].objectId }, SignedUrl: '', Activity: 'Signed', ipAddress: o.headers['x-real-ip'], }; let a; var f = (a = n.data.AuditTrail && 0 < n.data.AuditTrail.length ? [...n.data.AuditTrail, u] : [u]).filter(e => 'Signed' === e.Activity); let t = !1; !( (n.data.Signers && 0 < n.data.Signers.length && f.length !== n.data.Signers.length) || !(t = !0) ); var y, v, P, b, U, x, w = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`, I = './exports/' + w; let s = e.length; s = ( t ? ((y = n.data.Signers?.map(e => e.Name + ' <' + e.Email + '>')), (e = y && 0 < y.length ? ((v = await PDFDocument.load(e)), pdflibAddPlaceholder({ pdfDoc: v, reason: 'Digitally signed by OpenSign for ' + y?.join(', '), location: 'location', signatureLength: 15e3, }), (P = await v.save()), Buffer.from(P)) : ((b = await PDFDocument.load(e)), pdflibAddPlaceholder({ pdfDoc: b, reason: 'Digitally signed by OpenSign for ' + p + ' <' + m + '>', location: 'location', signatureLength: 15e3, }), (U = await b.save()), Buffer.from(U))), (x = await new SignPDF(e, h).signPDF()), fs.writeFileSync(I, x), x) : (fs.writeFileSync(I, e), e) ).length; var S, A, D, E = await uploadFile(w, I); if (E && E.imageUrl) return ( (S = await updateDoc( o.params.docId, E.imageUrl, r.data.results[0].objectId, o.headers['x-real-ip'], n.data, i )), (A = { url: E.imageUrl, sender: { Mail: n.data.ExtUserPtr.Email, Name: n.data.ExtUserPtr.Name }, pdfName: n.data.Name, receiver: m, }), n.data.IsSendMail && !1 === n.data.IsSendMail ? console.log("don't send mail") : sendMail(A), sendDoctoWebhook(n, E.imageUrl, 'signed', r?.data.results?.[0]), saveFileUsage(s, E.imageUrl, d.data.objectId), S && S.isCompleted && ((D = { url: E.imageUrl, sender: { Mail: n.data.ExtUserPtr.Email, Name: 'OpenSign™' }, pdfName: n.data.Name, receiver: n.data.ExtUserPtr.Email, }), n.data.IsSendMail && !1 === n.data.IsSendMail ? console.log("don't send mail") : sendCompletedMail(D), sendDoctoWebhook(n, E.imageUrl, 'completed')), fs.unlinkSync(I), console.log('New Signed PDF created called: ' + I), 'success' === S.message ? { status: 'success', data: E.imageUrl } : { status: 'error', message: 'please provide required parameters!' } ); } } } catch (e) { return ( console.log('Err ', e), 'ERR_BAD_REQUEST' === e.code ? { status: 'error', message: 'Invalid session token!' } : { status: 'error', message: 'Encrypted files are currently not supported!' } ); } } export default PDF;