mirror of
https://github.com/OpenSignLabs/OpenSign.git
synced 2026-08-25 17:12:37 +02:00
v2.12.0
feat: create duplicate template functionality feat: add support of csv and xlsx for bulk contacts import feat: add info text for forms and dashboard button feat: implement functionality to delete a PDF page while editing the document feat: show completed documents in which signers included but not owner in completed reports feat: add delete folder button in opensign drive feat: introduce Bcc email support for sending completed documents feat: allow merging multiple pdf while drafting document and template feat: add 'My Initials' tab for auto-signing in request-sign flow feat: add support for redirect URL to navigate after document completion feat: introduce privacy policy and digital signature terms before signing documents. feat: add feature to allow adding new pages to existing document feat: add save signature, initials, stamp functionality in sign pad for logged in user feat: add preferences menu feat: add save custom email template, notifyonsignature, set timezone, allow signature types in preferences feat: secure local url feat: implement Italian language translation feat: implement German language translation feat: update menu name from report to documents and shift contactbook in main menu feat: provide edit contact functionality fix: unable to delete folder when all its documents are deleted fix: fields.push is not function fix: document loading issue in opensign drive fix: adjust the guest signature flow to display the document in full screen, eliminating any blank space which is displayed below the place holder in mobile view fix: resolve issue of instance of pdfdict or pdfstream but got undefined build(deps): update dependencies refactor: change note text from add contact form
This commit is contained in:
@@ -1,35 +0,0 @@
|
||||
The OpenSign Enterprise license (the “Enterprise License”)
|
||||
Copyright (c) 2020-2024 Qik Innovations Private Limited.
|
||||
|
||||
With regard to the OpenSign Software:
|
||||
|
||||
This software and associated documentation files (the "Software") may only be
|
||||
used in production, if you (and any entity that you represent) have agreed to,
|
||||
and are in compliance with, the OpenSign Subscription Terms of Service(the “Enterprise Terms”), or other
|
||||
agreement governing the use of the Software, as agreed by you and OpenSign,
|
||||
and otherwise have a valid OpenSign Enterprise license for the
|
||||
correct number of user seats. Subject to the foregoing sentence, you are free to
|
||||
modify this Software and publish patches to the Software. You agree that OpenSign
|
||||
and/or its licensors (as applicable) retain all right, title and interest in and
|
||||
to all such modifications and/or patches, and all such modifications and/or
|
||||
patches may only be used, copied, modified, displayed, distributed, or otherwise
|
||||
exploited with a valid OpenSign Enterprise license for the correct
|
||||
number of user seats. Notwithstanding the foregoing, you may copy and modify
|
||||
the Software for development and testing purposes, without requiring a
|
||||
subscription. You agree that OpenSign and/or its licensors (as applicable) retain
|
||||
all right, title and interest in and to all such modifications. You are not
|
||||
granted any other rights beyond what is expressly stated herein. Subject to the
|
||||
foregoing, it is forbidden to copy, merge, publish, distribute, sublicense,
|
||||
and/or sell the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
For all third party components incorporated into the OpenSign Software, those
|
||||
components are licensed under the original license provided by the owner of the
|
||||
applicable component.
|
||||
@@ -1,192 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { cloudServerUrl } from '../../Utils.js';
|
||||
|
||||
// `replaceMailVaribles` is used to replace variables from mail with there actual values
|
||||
function replaceMailVaribles(subject, body, variables) {
|
||||
let replacedSubject = subject;
|
||||
let replacedBody = body;
|
||||
|
||||
for (const variable in variables) {
|
||||
const regex = new RegExp(`{{${variable}}}`, 'g');
|
||||
if (subject) {
|
||||
replacedSubject = replacedSubject.replace(regex, variables[variable]);
|
||||
}
|
||||
if (body) {
|
||||
replacedBody = replacedBody.replace(regex, variables[variable]);
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
subject: replacedSubject,
|
||||
body: replacedBody,
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
// `sendmail` is used to signing reminder mail to signer
|
||||
async function sendMail(doc, signer) {
|
||||
const subject = `{{sender_name}} has requested you to sign "{{document_title}}"`;
|
||||
const body = `<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body><p>Hi {{receiver_name}},</p><br><p>We hope this email finds you well. {{sender_name}} has requested you to review and sign <b>"{{document_title}}"</b>.</p><p>Your signature is crucial to proceed with the next steps as it signifies your agreement and authorization.</p><br><p>{{signing_url}}</p><br><p>If you have any questions or need further clarification regarding the document or the signing process, please contact the sender.</p><br><p>Thanks</p><p> Team OpenSign™</p><br></body> </html>`;
|
||||
const url = `${cloudServerUrl}/functions/sendmailv3`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': process.env.APP_ID,
|
||||
};
|
||||
|
||||
const baseUrl = new URL(process.env.PUBLIC_URL);
|
||||
const encodeBase64 = btoa(`${doc.objectId}/${signer.Email}/${signer.objectId}`);
|
||||
const expireDate = doc?.ExpiryDate?.iso;
|
||||
const newDate = new Date(expireDate);
|
||||
const localExpireDate = newDate.toLocaleDateString('en-US', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
});
|
||||
const signPdf = `${baseUrl.origin}/login/${encodeBase64}`;
|
||||
const variables = {
|
||||
document_title: doc.Name,
|
||||
sender_name: doc.ExtUserPtr.Name,
|
||||
sender_mail: doc.ExtUserPtr.Email,
|
||||
sender_phone: doc.ExtUserPtr?.Phone || '',
|
||||
receiver_name: signer.Name,
|
||||
receiver_email: signer.Email,
|
||||
receiver_phone: signer?.Phone || '',
|
||||
expiry_date: localExpireDate,
|
||||
company_name: doc?.ExtUserPtr?.Company || '',
|
||||
signing_url: `<a href=${signPdf} target=_blank>Sign here</a>`,
|
||||
};
|
||||
const mail = replaceMailVaribles(subject, body, variables);
|
||||
|
||||
let params = {
|
||||
mailProvider: doc?.ExtUserPtr?.active_mail_adapter,
|
||||
extUserId: doc?.ExtUserPtr?.objectId,
|
||||
recipient: signer.Email,
|
||||
subject: mail.subject,
|
||||
from: doc?.ExtUserPtr?.Email,
|
||||
html: mail.body,
|
||||
};
|
||||
try {
|
||||
// The axios request is used to send a signing reminder email.
|
||||
const res = await axios.post(url, params, { headers: headers });
|
||||
// console.log('res ', res.data.result);
|
||||
if (res.data.result.status === 'success') {
|
||||
return { status: 'success' };
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err in mail of sendreminder api', err);
|
||||
return { status: 'error' };
|
||||
}
|
||||
}
|
||||
export default async function autoReminder(request, response) {
|
||||
// The query below is used to find documents where the reminder date is less than or equal to the current date, and which have existing signers and a signed URL.
|
||||
try {
|
||||
const docQuery = new Parse.Query('contracts_Document');
|
||||
docQuery.limit(2000);
|
||||
docQuery.lessThanOrEqualTo('NextReminderDate', new Date());
|
||||
docQuery.equalTo('AutomaticReminders', true);
|
||||
docQuery.exists('NextReminderDate');
|
||||
docQuery.exists('Signers');
|
||||
docQuery.exists('SignedUrl');
|
||||
docQuery.descending('createdAt');
|
||||
docQuery.include('Signers,AuditTrail.UserPtr,ExtUserPtr,ExtUserPtr.TenantId');
|
||||
docQuery.notEqualTo('IsCompleted', true);
|
||||
docQuery.notEqualTo('IsDeclined', true);
|
||||
docQuery.notEqualTo('IsArchive', true);
|
||||
docQuery.greaterThanOrEqualTo('ExpiryDate', new Date());
|
||||
|
||||
const docsArr = await docQuery.find({ useMasterKey: true });
|
||||
|
||||
if (docsArr && docsArr.length > 0) {
|
||||
const _docsArr = JSON.parse(JSON.stringify(docsArr));
|
||||
let mailCount = 0;
|
||||
let docCount = 0;
|
||||
for (const doc of _docsArr) {
|
||||
// The reminderDate variable is used to calculate the next reminder date.
|
||||
const RemindOnceInEvery = doc?.RemindOnceInEvery || 5;
|
||||
const ReminderDate = new Date();
|
||||
ReminderDate.setDate(ReminderDate.getDate() + RemindOnceInEvery);
|
||||
// The sendInOrder variable is used to determine whether to send emails in order or not.
|
||||
const SendInOrder = doc?.SendinOrder || false;
|
||||
if (SendInOrder) {
|
||||
// The auditTrail variable is used to get the count of how many users have already signed the document.
|
||||
const auditTrail = doc?.AuditTrail?.filter(x => x.Activity === 'Signed');
|
||||
const count = auditTrail?.length || 0;
|
||||
const signer = doc?.Signers?.[count];
|
||||
if (signer) {
|
||||
docCount += 1;
|
||||
const mailRes = await sendMail(doc, signer);
|
||||
if (mailRes && mailRes.status === 'success') {
|
||||
mailCount += 1;
|
||||
}
|
||||
try {
|
||||
// The code below is used to update the next reminder date of the document based on the "remind once every X days" setting.
|
||||
const updateDoc = new Parse.Object('contracts_Document');
|
||||
updateDoc.id = doc.objectId;
|
||||
updateDoc.set('NextReminderDate', ReminderDate);
|
||||
const updateRes = await updateDoc.save(null, { useMasterKey: true });
|
||||
// console.log('updateRes ', updateRes);
|
||||
} catch (err) {
|
||||
console.log('err in update document', err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// The AuditTrail variable is used to check if there is any user who has already signed the document.
|
||||
const auditTrail = doc?.AuditTrail?.filter(x => x.Activity === 'Signed');
|
||||
if (auditTrail?.length > 0) {
|
||||
// The signers variable is used to get the signers who haven't signed the document.
|
||||
const signers = doc?.Signers.filter(signer => {
|
||||
const signedUser = auditTrail?.find(y => y.UserPtr.objectId === signer.objectId);
|
||||
if (!signedUser) {
|
||||
return signer;
|
||||
}
|
||||
});
|
||||
if (signers?.length > 0) {
|
||||
docCount += 1;
|
||||
// The for...of loop below is used to send a signing reminder to every signer who hasn't signed the document yet.
|
||||
for (const signer of signers) {
|
||||
const mailRes = await sendMail(doc, signer);
|
||||
if (mailRes && mailRes.status === 'success') {
|
||||
mailCount += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// The for...of loop below is used to send a signing reminder to every signer who hasn't signed the document yet.
|
||||
const signers = doc?.Signers;
|
||||
if (signers?.length > 0) {
|
||||
docCount += 1;
|
||||
for (const signer of signers) {
|
||||
const mailRes = await sendMail(doc, signer);
|
||||
if (mailRes && mailRes.status === 'success') {
|
||||
mailCount += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The code below is used to update the next reminder date of the document based on the "remind once every X days" setting.
|
||||
try {
|
||||
const updateDoc = new Parse.Object('contracts_Document');
|
||||
updateDoc.id = doc.objectId;
|
||||
updateDoc.set('NextReminderDate', ReminderDate);
|
||||
const updateRes = await updateDoc.save(null, { useMasterKey: true });
|
||||
// console.log('updateRes ', updateRes);
|
||||
} catch (err) {
|
||||
console.log('err in sendmail', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (docCount > 0) {
|
||||
response.json({ status: 'success', document_count: docCount, mail_count: mailCount });
|
||||
} else {
|
||||
response.json({ status: 'no record found' });
|
||||
}
|
||||
} else {
|
||||
response.json({ status: 'no record found' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
const code = err?.code || 400;
|
||||
const message = err?.message || 'Somehting went wrong!';
|
||||
response.status(code).json({ error: message });
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,8 @@
|
||||
//--npm modules
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import dotenv from 'dotenv';
|
||||
import uploadFile from './uploadFile.js';
|
||||
import saveSubscription from './saveSubscription.js';
|
||||
import saveInvoice from './saveInvoice.js';
|
||||
import savePayments from './savePayments.js';
|
||||
import gooogleauth from './googleauth.js';
|
||||
import autoReminder from './autoReminder.js';
|
||||
import validateSmtp from './validateSmtp.js';
|
||||
|
||||
export const app = express();
|
||||
|
||||
dotenv.config();
|
||||
@@ -18,9 +12,3 @@ app.use(express.urlencoded({ limit: '50mb', extended: true }));
|
||||
|
||||
app.post('/file_upload', uploadFile);
|
||||
|
||||
app.post('/savesubscription', saveSubscription);
|
||||
app.post('/saveinvoice', saveInvoice);
|
||||
app.post('/savepayment', savePayments);
|
||||
app.post('/googleauth', gooogleauth);
|
||||
app.post('/sendreminder', autoReminder);
|
||||
app.post('/validatesmtp', validateSmtp);
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { cloudServerUrl } from '../../Utils.js';
|
||||
const appId = process.env.APP_ID;
|
||||
const serverUrl = cloudServerUrl; //process.env.SERVER_URL;
|
||||
export default async function gooogleauth(request, response) {
|
||||
const code = request.body.code;
|
||||
const baseUrl = new URL(process.env.SERVER_URL);
|
||||
|
||||
try {
|
||||
const userRes = await axios.get(serverUrl + '/users/me', {
|
||||
headers: {
|
||||
'X-Parse-Application-Id': appId,
|
||||
'X-Parse-Session-Token': request.headers['sessiontoken'],
|
||||
},
|
||||
});
|
||||
const userId = userRes.data && userRes.data.objectId;
|
||||
if (userId) {
|
||||
const clientId = process.env.GOOGLE_CLIENT_ID;
|
||||
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
|
||||
const redirectUri =
|
||||
baseUrl?.hostname === 'localhost'
|
||||
? 'http://localhost:3000'
|
||||
: 'https://console.opensignlabs.com'; // Should match the redirect URI used in the authorization request
|
||||
const tokenEndpoint = 'https://oauth2.googleapis.com/token';
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.append('code', code);
|
||||
params.append('client_id', clientId);
|
||||
params.append('client_secret', clientSecret);
|
||||
params.append('redirect_uri', redirectUri);
|
||||
params.append('grant_type', 'authorization_code');
|
||||
|
||||
const res = await axios.post(tokenEndpoint, params);
|
||||
// console.log('oauthres ', res.data);
|
||||
const refresh_token = res.data.refresh_token;
|
||||
const extUserCls = new Parse.Query('contracts_Users');
|
||||
extUserCls.equalTo('UserId', { __type: 'Pointer', className: '_User', objectId: userId });
|
||||
const extUser = await extUserCls.first({ useMasterKey: true });
|
||||
|
||||
if (extUser) {
|
||||
const extUserCls = new Parse.Object('contracts_Users');
|
||||
extUserCls.id = extUser.id;
|
||||
extUserCls.set('google_refresh_token', refresh_token);
|
||||
extUserCls.set('active_mail_adapter', 'google');
|
||||
const updateExtUser = await extUserCls.save(null, { useMasterKey: true });
|
||||
// console.log('updateExtUser ', updateExtUser);
|
||||
}
|
||||
return response.status(200).json({ status: 'success' });
|
||||
} else {
|
||||
return response.status(404).json({ message: 'user not found!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err in google auth', err);
|
||||
if (err?.response?.data?.error) {
|
||||
return response.status(404).json({ message: err.response.data.error });
|
||||
} else {
|
||||
return response.status(404).json({ message: err.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
export default async function saveInvoice(request, response) {
|
||||
const InvoiceId = request.body.data.invoice.invoice_id;
|
||||
const body = request.body;
|
||||
const Email = request.body.data.invoice.email;
|
||||
|
||||
try {
|
||||
const extUserCls = new Parse.Query('contracts_Users');
|
||||
extUserCls.equalTo('Email', Email);
|
||||
const extUser = await extUserCls.first({ useMasterKey: true });
|
||||
if (extUser) {
|
||||
const invoiceCls = new Parse.Query('contracts_Invoices');
|
||||
invoiceCls.equalTo('InvoiceId', InvoiceId);
|
||||
const invoice = await invoiceCls.first({ useMasterKey: true });
|
||||
if (invoice) {
|
||||
const updateInvoice = new Parse.Object('contracts_Invoices');
|
||||
updateInvoice.id = invoice.id;
|
||||
updateInvoice.set('InvoiceDetails', body);
|
||||
await updateInvoice.save(null, { useMasterKey: true });
|
||||
return response.status(200).json({ status: 'update invoice!' });
|
||||
} else {
|
||||
const createInvoice = new Parse.Object('contracts_Invoices');
|
||||
createInvoice.set('InvoiceId', InvoiceId);
|
||||
createInvoice.set('InvoiceDetails', body);
|
||||
createInvoice.set('ExtUserPtr', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Users',
|
||||
objectId: extUser.id,
|
||||
});
|
||||
createInvoice.set('CreatedBy', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: extUser.get('UserId').id,
|
||||
});
|
||||
if (extUser?.get('TenantId')?.id) {
|
||||
createInvoice.set('TenantId', {
|
||||
__type: 'Pointer',
|
||||
className: 'partners_Tenant',
|
||||
objectId: extUser.get('TenantId').id,
|
||||
});
|
||||
}
|
||||
await createInvoice.save(null, { useMasterKey: true });
|
||||
return response.status(200).json({ status: 'create invoice!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(404).json({ status: 'user not found!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Err in save invoice', err);
|
||||
return response.status(400).json({ status: 'error:' + err.message });
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
export default async function savePayments(request, response) {
|
||||
const PaymentId = request.body.data.payment.payment_id;
|
||||
const body = request.body;
|
||||
const Email = request.body.data.payment.email;
|
||||
try {
|
||||
const extUserCls = new Parse.Query('contracts_Users');
|
||||
extUserCls.equalTo('Email', Email);
|
||||
const extUser = await extUserCls.first({ useMasterKey: true });
|
||||
if (extUser) {
|
||||
const paymentCls = new Parse.Query('contracts_Payments');
|
||||
paymentCls.equalTo('PaymentId', PaymentId);
|
||||
const payment = await paymentCls.first({ useMasterKey: true });
|
||||
if (payment) {
|
||||
const updatePayment = new Parse.Object('contracts_Payments');
|
||||
updatePayment.id = payment.id;
|
||||
updatePayment.set('PaymentDetails', body);
|
||||
await updatePayment.save(null, { useMasterKey: true });
|
||||
return response.status(200).json({ status: 'update Payment!' });
|
||||
} else {
|
||||
const createPayment = new Parse.Object('contracts_Payments');
|
||||
createPayment.set('PaymentId', PaymentId);
|
||||
createPayment.set('PaymentDetails', body);
|
||||
createPayment.set('ExtUserPtr', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Users',
|
||||
objectId: extUser.id,
|
||||
});
|
||||
createPayment.set('CreatedBy', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: extUser.get('UserId').id,
|
||||
});
|
||||
if (extUser?.get('TenantId')?.id) {
|
||||
createPayment.set('TenantId', {
|
||||
__type: 'Pointer',
|
||||
className: 'partners_Tenant',
|
||||
objectId: extUser.get('TenantId').id,
|
||||
});
|
||||
}
|
||||
await createPayment.save(null, { useMasterKey: true });
|
||||
return response.status(200).json({ status: 'create payments!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(404).json({ status: 'user not found!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Err in save payment', err);
|
||||
return response.status(400).json({ status: 'error:' + err.message });
|
||||
}
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
import { planCredits } from '../../Utils.js';
|
||||
|
||||
export default async function saveSubscription(request, response) {
|
||||
const SubscriptionId = request.body?.data?.subscription?.subscription_id;
|
||||
const body = request.body;
|
||||
const Email = request.body.data?.subscription?.customer?.email;
|
||||
const Next_billing_date = request.body?.data?.subscription?.next_billing_at;
|
||||
const planCode = request.body?.data?.subscription?.plan?.plan_code;
|
||||
const addons = request.body?.data?.subscription?.addons || [];
|
||||
const event = request.body?.data?.event_type || '';
|
||||
const credits = planCredits?.[planCode] || 0;
|
||||
const isTeamPlan = planCode?.includes('team');
|
||||
let newAddons = 0;
|
||||
if (addons?.length > 0) {
|
||||
let allowedUsersMonthly = 0;
|
||||
let allowedUsersYearly = 0;
|
||||
addons?.forEach(item => {
|
||||
if (item.addon_code === 'extra-teams-users-monthly') {
|
||||
allowedUsersMonthly += item.quantity;
|
||||
} else if (item.addon_code === 'extra-teams-users-yearly') {
|
||||
allowedUsersYearly += item.quantity;
|
||||
} else if (item.addon_code === 'extra-users') {
|
||||
allowedUsersMonthly += item.quantity;
|
||||
}
|
||||
});
|
||||
if (allowedUsersMonthly > 0 || allowedUsersYearly > 0) {
|
||||
newAddons = allowedUsersMonthly + allowedUsersYearly + 1;
|
||||
}
|
||||
} else {
|
||||
if (planCode === 'teams-yearly' || planCode === 'teams-monthly' || planCode === 'team-weekly') {
|
||||
newAddons = 1;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const extUserCls = new Parse.Query('contracts_Users');
|
||||
extUserCls.equalTo('Email', Email);
|
||||
const extUser = await extUserCls.first({ useMasterKey: true });
|
||||
if (extUser) {
|
||||
const subcriptionCls = new Parse.Query('contracts_Subscriptions');
|
||||
subcriptionCls.equalTo('TenantId', {
|
||||
__type: 'Pointer',
|
||||
className: 'partners_Tenant',
|
||||
objectId: extUser.get('TenantId').id,
|
||||
});
|
||||
const subscription = await subcriptionCls.first({ useMasterKey: true });
|
||||
if (subscription) {
|
||||
const _resSub = JSON.parse(JSON.stringify(subscription));
|
||||
const updateSubscription = new Parse.Object('contracts_Subscriptions');
|
||||
updateSubscription.id = subscription.id;
|
||||
updateSubscription.set('SubscriptionId', SubscriptionId);
|
||||
updateSubscription.set('SubscriptionDetails', body);
|
||||
if (Next_billing_date) {
|
||||
updateSubscription.set('Next_billing_date', new Date(Next_billing_date));
|
||||
} else {
|
||||
updateSubscription.unset('Next_billing_date');
|
||||
}
|
||||
updateSubscription.set('PlanCode', planCode);
|
||||
if (newAddons > 0) {
|
||||
updateSubscription.set('AllowedUsers', parseInt(newAddons));
|
||||
}
|
||||
let existAddon = 0;
|
||||
let allowedUsersMonthly = 0;
|
||||
let allowedUsersYearly = 0;
|
||||
_resSub.SubscriptionDetails?.data?.subscription?.addons?.forEach(item => {
|
||||
if (item.addon_code === 'extra-teams-users-monthly') {
|
||||
allowedUsersMonthly += item.quantity;
|
||||
} else if (item.addon_code === 'extra-teams-users-yearly') {
|
||||
allowedUsersYearly += item.quantity;
|
||||
} else if (item.addon_code === 'extra-users') {
|
||||
allowedUsersMonthly += item.quantity;
|
||||
}
|
||||
});
|
||||
if (allowedUsersMonthly > 0 || allowedUsersYearly > 0) {
|
||||
existAddon = allowedUsersMonthly + allowedUsersYearly + 1; // + 1 is Admin user
|
||||
} else {
|
||||
if (
|
||||
planCode === 'teams-yearly' ||
|
||||
planCode === 'teams-monthly' ||
|
||||
planCode === 'team-weekly'
|
||||
) {
|
||||
existAddon = 1; // 1 is Admin user
|
||||
}
|
||||
}
|
||||
const isSameAsPrevPlan = subscription?.get('PlanCode') === planCode;
|
||||
if (isSameAsPrevPlan) {
|
||||
const planCredits = subscription?.get('PlanCredits');
|
||||
const existAllowedCredits = subscription?.get('AllowedCredits') || 0;
|
||||
if (planCredits) {
|
||||
const oldAddons = existAddon;
|
||||
const substractedAddon = newAddons - oldAddons;
|
||||
if (isTeamPlan && substractedAddon > 0) {
|
||||
const newCredits = existAllowedCredits + substractedAddon * planCredits;
|
||||
updateSubscription.set('AllowedCredits', newCredits);
|
||||
if (event === 'subscription_created') {
|
||||
updateSubscription.set('PlanCredits', credits);
|
||||
}
|
||||
} else if (isTeamPlan) {
|
||||
const existCredits = existAddon * planCredits;
|
||||
updateSubscription.set('AllowedCredits', existCredits);
|
||||
if (event === 'subscription_created') {
|
||||
updateSubscription.set('PlanCredits', credits);
|
||||
}
|
||||
} else {
|
||||
updateSubscription.set('AllowedCredits', planCredits);
|
||||
if (event === 'subscription_created') {
|
||||
updateSubscription.set('PlanCredits', credits);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (credits > 0) {
|
||||
if (isTeamPlan) {
|
||||
const newCredits = newAddons * credits;
|
||||
updateSubscription.set('AllowedCredits', newCredits);
|
||||
updateSubscription.set('PlanCredits', credits);
|
||||
} else {
|
||||
updateSubscription.set('AllowedCredits', credits);
|
||||
updateSubscription.set('PlanCredits', credits);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (credits > 0) {
|
||||
if (isTeamPlan) {
|
||||
const newCredits = newAddons * credits;
|
||||
updateSubscription.set('AllowedCredits', newCredits);
|
||||
updateSubscription.set('PlanCredits', credits);
|
||||
} else {
|
||||
updateSubscription.set('AllowedCredits', credits);
|
||||
updateSubscription.set('PlanCredits', credits);
|
||||
}
|
||||
}
|
||||
}
|
||||
await updateSubscription.save(null, { useMasterKey: true });
|
||||
return response.status(200).json({ status: 'update subscription!' });
|
||||
} else {
|
||||
const createSubscription = new Parse.Object('contracts_Subscriptions');
|
||||
createSubscription.set('SubscriptionId', SubscriptionId);
|
||||
createSubscription.set('SubscriptionDetails', body);
|
||||
createSubscription.set('ExtUserPtr', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Users',
|
||||
objectId: extUser.id,
|
||||
});
|
||||
createSubscription.set('CreatedBy', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: extUser.get('UserId').id,
|
||||
});
|
||||
createSubscription.set('TenantId', {
|
||||
__type: 'Pointer',
|
||||
className: 'partners_Tenant',
|
||||
objectId: extUser.get('TenantId').id,
|
||||
});
|
||||
if (Next_billing_date) {
|
||||
createSubscription.set('Next_billing_date', new Date(Next_billing_date));
|
||||
} else {
|
||||
createSubscription.unset('Next_billing_date');
|
||||
}
|
||||
createSubscription.set('PlanCode', planCode);
|
||||
if (newAddons > 0) {
|
||||
createSubscription.set('AllowedUsers', parseInt(newAddons));
|
||||
}
|
||||
if (credits > 0) {
|
||||
if (isTeamPlan) {
|
||||
const totalCredits = parseInt(newAddons) * credits;
|
||||
createSubscription.set('AllowedCredits', totalCredits);
|
||||
createSubscription.set('PlanCredits', credits);
|
||||
} else {
|
||||
createSubscription.set('AllowedCredits', credits);
|
||||
createSubscription.set('PlanCredits', credits);
|
||||
}
|
||||
}
|
||||
await createSubscription.save(null, { useMasterKey: true });
|
||||
return response.status(200).json({ status: 'create subscription!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(404).json({ status: 'user not found!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Err in save subscription', err);
|
||||
return response.status(400).json({ status: 'error:' + err.message });
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
//--npm modules
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
export const app = express();
|
||||
import dotenv from 'dotenv';
|
||||
import getUser from './routes/getUser.js';
|
||||
import getDocumentList from './routes/getDocumentList.js';
|
||||
import getDocument from './routes/getDocument.js';
|
||||
import getContact from './routes/getContact.js';
|
||||
import deleteContact from './routes/deleteContact.js';
|
||||
import getContactList from './routes/getContactList.js';
|
||||
import getTemplate from './routes/getTemplate.js';
|
||||
import deletedTemplate from './routes/deleteTemplate.js';
|
||||
import getTemplatetList from './routes/getTemplateList.js';
|
||||
import updateTemplate from './routes/updateTemplate.js';
|
||||
import createContact from './routes/createContact.js';
|
||||
import multer from 'multer';
|
||||
import updateDocument from './routes/updateDocument.js';
|
||||
import deleteDocument from './routes/deleteDocument.js';
|
||||
import createDocumentWithTemplate from './routes/CreateDocumentWithTemplate.js';
|
||||
import saveWebhook from './routes/saveWebhook.js';
|
||||
import deleteWebhook from './routes/deleteWebhook.js';
|
||||
import getWebhook from './routes/getWebhook.js';
|
||||
import createDocumentwithCoordinate from './routes/createDocumentwithCoordinate.js';
|
||||
import createTemplatewithCoordinate from './routes/createTemplatewithCoordinate.js';
|
||||
import resendMail from './routes/resendMail.js';
|
||||
import getFolder from './routes/getFolder.js';
|
||||
import createFolder from './routes/createFolder.js';
|
||||
import updateFolder from './routes/updateFolder.js';
|
||||
import getFolderList from './routes/getFolderList.js';
|
||||
import deleteFolder from './routes/deleteFolder.js';
|
||||
dotenv.config();
|
||||
const storage = multer.memoryStorage();
|
||||
const upload = multer({ storage: storage });
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: '50mb' }));
|
||||
app.use(express.urlencoded({ limit: '50mb', extended: true }));
|
||||
|
||||
// get user details whose api token used
|
||||
app.get('/getuser', getUser);
|
||||
|
||||
// get contact on the basis of id
|
||||
app.post('/createcontact', createContact);
|
||||
|
||||
// get contact on the basis of id
|
||||
app.get('/contact/:contact_id', getContact);
|
||||
|
||||
// soft delete contact
|
||||
app.delete('/contact/:contact_id', deleteContact);
|
||||
|
||||
// get list of contacts
|
||||
app.get('/contactlist', getContactList);
|
||||
|
||||
// create Document
|
||||
app.post('/createdocumentwithbinary', upload.array('file', 1), createDocumentwithCoordinate);
|
||||
|
||||
// create Document with co-ordinate
|
||||
app.post('/createdocument', createDocumentwithCoordinate);
|
||||
|
||||
// create Document with templateId
|
||||
app.post('/createdocument/:template_id', createDocumentWithTemplate);
|
||||
|
||||
// get Document on the basis of id
|
||||
app.get('/document/:document_id', getDocument);
|
||||
|
||||
// get document on the basis of id
|
||||
app.put('/document/:document_id', updateDocument);
|
||||
|
||||
// get document on the basis of id
|
||||
app.delete('/document/:document_id', deleteDocument);
|
||||
|
||||
// get all types of documents on the basis of doctype
|
||||
app.get('/documentlist/:doctype', getDocumentList);
|
||||
|
||||
// create Template with co-ordinate
|
||||
app.post('/createtemplate', createTemplatewithCoordinate);
|
||||
|
||||
// create Template with binary
|
||||
app.post('/createtemplatewithbinary', upload.array('file', 1), createTemplatewithCoordinate);
|
||||
|
||||
// get template on the basis of id
|
||||
app.get('/template/:template_id', getTemplate);
|
||||
|
||||
// get template on the basis of id
|
||||
app.put('/template/:template_id', updateTemplate);
|
||||
|
||||
// get template on the basis of id
|
||||
app.delete('/template/:template_id', deletedTemplate);
|
||||
|
||||
// get all types of documents on the basis of doctype
|
||||
app.get('/templatelist', getTemplatetList);
|
||||
|
||||
// set and update webhook
|
||||
app.get('/webhook', getWebhook);
|
||||
|
||||
// set and update webhook
|
||||
app.post('/webhook', saveWebhook);
|
||||
|
||||
// set and update webhook
|
||||
app.delete('/webhook', deleteWebhook);
|
||||
|
||||
// resend mail
|
||||
app.post('/resendmail', resendMail);
|
||||
|
||||
// create folder
|
||||
app.post('/createfolder', createFolder);
|
||||
|
||||
// update folder
|
||||
app.put('/folder/:folder_id', updateFolder);
|
||||
|
||||
// get folder list
|
||||
app.delete('/folder/:folder_id', deleteFolder);
|
||||
|
||||
// get folder
|
||||
app.get('/folder/:folder_id', getFolder);
|
||||
|
||||
// get folder list
|
||||
app.get('/folderlist', getFolderList);
|
||||
@@ -1,435 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { cloudServerUrl, customAPIurl, replaceMailVaribles } from '../../../../Utils.js';
|
||||
|
||||
// `sendDoctoWebhook` is used to send res data of document on webhook
|
||||
async function sendDoctoWebhook(doc, WebhookUrl, userId) {
|
||||
if (WebhookUrl) {
|
||||
const params = { event: 'created', ...doc };
|
||||
await axios
|
||||
.post(WebhookUrl, params, { headers: { 'Content-Type': 'application/json' } })
|
||||
.then(res => {
|
||||
try {
|
||||
// console.log('res ', res);
|
||||
const webhook = new Parse.Object('contracts_Webhook');
|
||||
webhook.set('Log', res?.status);
|
||||
webhook.set('UserId', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: userId,
|
||||
});
|
||||
webhook.save(null, { useMasterKey: true });
|
||||
} catch (err) {
|
||||
console.log('err save in contracts_Webhook', err);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.log('Err send data to webhook', err);
|
||||
try {
|
||||
const webhook = new Parse.Object('contracts_Webhook');
|
||||
webhook.set('Log', err?.status);
|
||||
webhook.set('UserId', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: userId,
|
||||
});
|
||||
webhook.save(null, { useMasterKey: true });
|
||||
} catch (err) {
|
||||
console.log('err save in contracts_Webhook', err);
|
||||
}
|
||||
});
|
||||
// console.log('res ', res.data);
|
||||
}
|
||||
}
|
||||
export default async function createDocumentWithTemplate(request, response) {
|
||||
const signers = request.body.signers;
|
||||
const folderId = request.body.folderId;
|
||||
const templateId = request.params.template_id;
|
||||
const protocol = customAPIurl();
|
||||
const baseUrl = new URL(process.env.PUBLIC_URL);
|
||||
const send_email = request.body.send_email;
|
||||
const email_subject = request.body.email_subject;
|
||||
const email_body = request.body.email_body;
|
||||
const sendInOrder = request.body.sendInOrder || true;
|
||||
const TimeToCompleteDays = request.body.timeToCompleteDays || 15;
|
||||
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const extUsers = new Parse.Query('contracts_Users');
|
||||
extUsers.equalTo('UserId', userPtr);
|
||||
const extUser = await extUsers.first({ useMasterKey: true });
|
||||
|
||||
const subscription = new Parse.Query('contracts_Subscriptions');
|
||||
subscription.equalTo('TenantId', {
|
||||
__type: 'Pointer',
|
||||
className: 'partners_Tenant',
|
||||
objectId: extUser.get('TenantId').id,
|
||||
});
|
||||
subscription.include('ExtUserPtr');
|
||||
subscription.greaterThanOrEqualTo('Next_billing_date', new Date());
|
||||
const resSub = await subscription.first({ useMasterKey: true });
|
||||
if (resSub) {
|
||||
const _resSub = JSON.parse(JSON.stringify(resSub));
|
||||
const allowedCredits = _resSub?.AllowedCredits || 0;
|
||||
const addonCredits = _resSub?.AddonCredits || 0;
|
||||
const totalcredits = allowedCredits + addonCredits;
|
||||
if (totalcredits > 0) {
|
||||
const templateQuery = new Parse.Query('contracts_Template');
|
||||
templateQuery.include('ExtUserPtr');
|
||||
templateQuery.include('ExtUserPtr.TenantId');
|
||||
const templateRes = await templateQuery.get(templateId, { useMasterKey: true });
|
||||
if (templateRes) {
|
||||
const template = JSON.parse(JSON.stringify(templateRes));
|
||||
if (template?.Placeholders?.length > 0) {
|
||||
const emptyplaceholder = template?.Placeholders.filter(x => !x.signerObjId);
|
||||
const isValid =
|
||||
signers.length >= emptyplaceholder.length &&
|
||||
signers.length <= template?.Placeholders?.length;
|
||||
const placeholder =
|
||||
signers.length > emptyplaceholder.length ? template.Placeholders : emptyplaceholder;
|
||||
const updateSigners = placeholder.every(y => signers?.some(x => x.role === y.Role));
|
||||
// console.log('isValid ', isValid);
|
||||
if (isValid && updateSigners) {
|
||||
//Check if every item's placeholders contain at least one placeholder with type 'signature'.
|
||||
let isSignature = template?.Placeholders?.every(item =>
|
||||
item?.placeHolder.some(x => x?.pos.some(data => data?.type === 'signature'))
|
||||
);
|
||||
if (!isSignature) {
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'Please add at least one signature widget for all signers' });
|
||||
}
|
||||
const folderPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Document',
|
||||
objectId: folderId,
|
||||
};
|
||||
const object = new Parse.Object('contracts_Document');
|
||||
object.set('Name', template.Name);
|
||||
if (template?.Note) {
|
||||
object.set('Note', template.Note);
|
||||
}
|
||||
if (template?.Description) {
|
||||
object.set('Description', template.Description);
|
||||
}
|
||||
object.set('IsSendMail', send_email);
|
||||
if (sendInOrder) {
|
||||
object.set('SendinOrder', sendInOrder);
|
||||
} else if (template?.SendinOrder && template?.SendinOrder) {
|
||||
object.set('SendinOrder', template?.SendinOrder);
|
||||
}
|
||||
let templateSigner = template?.Signers ? template?.Signers : [];
|
||||
let contact = [];
|
||||
if (signers && signers.length > 0) {
|
||||
let parseSigners = [...signers];
|
||||
let createContactUrl = protocol + '/v1/createcontact';
|
||||
|
||||
for (const obj of parseSigners) {
|
||||
const body = {
|
||||
name: obj?.name || '',
|
||||
email: obj?.email || '',
|
||||
phone: obj?.phone || '',
|
||||
};
|
||||
try {
|
||||
const res = await axios.post(createContactUrl, body, {
|
||||
headers: { 'Content-Type': 'application/json', 'x-api-token': reqToken },
|
||||
});
|
||||
const contactPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Contactbook',
|
||||
objectId: res.data?.objectId,
|
||||
};
|
||||
const newObj = { ...obj, contactPtr: contactPtr };
|
||||
contact.push(newObj);
|
||||
} catch (err) {
|
||||
// console.log('err ', err);
|
||||
if (err?.response?.data?.objectId) {
|
||||
const contactPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Contactbook',
|
||||
objectId: err.response.data?.objectId,
|
||||
};
|
||||
const newObj = { ...obj, contactPtr: contactPtr };
|
||||
contact.push(newObj);
|
||||
} else {
|
||||
console.log('err ', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
const contactPtrs = contact.map(x => x.contactPtr);
|
||||
object.set('Signers', [...templateSigner, ...contactPtrs]);
|
||||
|
||||
let updatedPlaceholder = template?.Placeholders?.map(x => {
|
||||
let matchingSigner = contact.find(y => x.Role && x.Role === y.role);
|
||||
|
||||
if (matchingSigner) {
|
||||
return {
|
||||
...x,
|
||||
signerObjId: matchingSigner?.contactPtr?.objectId,
|
||||
signerPtr: matchingSigner?.contactPtr,
|
||||
};
|
||||
} else {
|
||||
return { ...x };
|
||||
}
|
||||
});
|
||||
object.set('Placeholders', updatedPlaceholder);
|
||||
} else {
|
||||
object.set('Signers', templateSigner);
|
||||
}
|
||||
object.set('URL', template.URL);
|
||||
object.set('SignedUrl', template.URL);
|
||||
object.set('SentToOthers', true);
|
||||
if (TimeToCompleteDays) {
|
||||
object.set('TimeToCompleteDays', TimeToCompleteDays);
|
||||
}
|
||||
const enableOTP = request.body?.enableOTP;
|
||||
const IsEnableOTP =
|
||||
enableOTP !== undefined ? enableOTP : template?.IsEnableOTP || false;
|
||||
const enableTour = request.body?.enableTour;
|
||||
const isTourEnabled =
|
||||
enableTour !== undefined ? enableTour : template?.IsTourEnabled || false;
|
||||
object.set('IsTourEnabled', isTourEnabled);
|
||||
object.set('IsEnableOTP', IsEnableOTP);
|
||||
object.set('CreatedBy', template.CreatedBy);
|
||||
object.set('ExtUserPtr', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Users',
|
||||
objectId: template.ExtUserPtr.objectId,
|
||||
});
|
||||
if (folderId) {
|
||||
object.set('Folder', folderPtr);
|
||||
}
|
||||
if (template?.FileAdapterId) {
|
||||
object.set('FileAdapterId', template?.FileAdapterId);
|
||||
}
|
||||
const newACL = new Parse.ACL();
|
||||
newACL.setPublicReadAccess(false);
|
||||
newACL.setPublicWriteAccess(false);
|
||||
newACL.setReadAccess(userPtr.objectId, true);
|
||||
newACL.setWriteAccess(userPtr.objectId, true);
|
||||
object.setACL(newACL);
|
||||
const res = await object.save(null, { useMasterKey: true });
|
||||
|
||||
const newDate = new Date();
|
||||
newDate.setDate(newDate.getDate() + 15);
|
||||
const localExpireDate = newDate.toLocaleDateString('en-US', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
});
|
||||
let sender = template.ExtUserPtr.Email;
|
||||
let sendMail;
|
||||
if (send_email === false) {
|
||||
console.log("don't send mail");
|
||||
} else {
|
||||
let contactMail = contact;
|
||||
if (sendInOrder) {
|
||||
contactMail = contact.slice();
|
||||
contactMail.splice(1);
|
||||
}
|
||||
for (let i = 0; i < contactMail.length; i++) {
|
||||
try {
|
||||
const imgPng = 'https://qikinnovation.ams3.digitaloceanspaces.com/logo.png';
|
||||
let url = `${cloudServerUrl}/functions/sendmailv3/`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': process.env.APP_ID,
|
||||
'X-Parse-Master-Key': process.env.MASTER_KEY,
|
||||
};
|
||||
|
||||
const objectId = contactMail[i].contactPtr.objectId;
|
||||
const hostUrl = baseUrl.origin;
|
||||
//encode this url value `${res.id}/${contactMail[i].email}/${objectId}` to base64 using `btoa` function
|
||||
const encodeBase64 = btoa(`${res.id}/${contactMail[i].email}/${objectId}`);
|
||||
let signPdf = `${hostUrl}/login/${encodeBase64}`;
|
||||
const openSignUrl = 'https://www.opensignlabs.com/contact-us';
|
||||
const orgName = template.ExtUserPtr.Company
|
||||
? template.ExtUserPtr.Company
|
||||
: '';
|
||||
const themeBGcolor = '#47a3ad';
|
||||
const email_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: white;padding-bottom: 20px;'> <div style='padding:10px 10px 0 10px'><img src='" +
|
||||
imgPng +
|
||||
"' height='50' style='padding:20px; width:170px; height:40px;' /></div><div style='padding: 2px;font-family: system-ui;background-color:" +
|
||||
themeBGcolor +
|
||||
";'><p style='font-size: 20px;font-weight: 400;color: white;padding-left: 20px;' > Digital Signature Request</p></div><div><p style='padding: 20px;font-family: system-ui;font-size: 14px; margin-bottom: 10px;'> " +
|
||||
template.ExtUserPtr.Name +
|
||||
' has requested you to review and sign <strong> ' +
|
||||
template.Name +
|
||||
"</strong>.</p><div style='padding: 5px 0px 5px 25px;display: flex;flex-direction: row;justify-content: space-around;'><table> <tr> <td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Sender</td> <td> </td> <td style='color:#626363;font-weight:bold'>" +
|
||||
sender +
|
||||
"</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Organization</td> <td> </td><td style='color:#626363;font-weight:bold'> " +
|
||||
orgName +
|
||||
"</td></tr> <tr> <td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Expires on</td><td> </td> <td style='color:#626363;font-weight:bold'>" +
|
||||
localExpireDate +
|
||||
"</td></tr><tr> <td></td> <td> </td></tr></table> </div> <div style='margin-left:70px'><a target=_blank href=" +
|
||||
signPdf +
|
||||
"> <button style='padding: 12px 12px 12px 12px;background-color: #d46b0f;color: white; border: 0px;box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px,rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;font-weight:bold;margin-top:30px;'>Sign here</button></a> </div> <div style='display: flex; justify-content: center;margin-top: 10px;'> </div></div></div><div><p> This is an automated email from OpenSign™. For any queries regarding this email, please contact the sender " +
|
||||
sender +
|
||||
' directly.If you think this email is inappropriate or spam, you may file a complaint with OpenSign™ <a href=' +
|
||||
openSignUrl +
|
||||
' target=_blank>here</a>.</p> </div></div></body> </html>';
|
||||
|
||||
let replaceVar;
|
||||
const variables = {
|
||||
document_title: template.Name,
|
||||
sender_name: template.ExtUserPtr.Name,
|
||||
sender_mail: template.ExtUserPtr.Email,
|
||||
sender_phone: template.ExtUserPtr?.Phone || '',
|
||||
receiver_name: contactMail[i].name,
|
||||
receiver_email: contactMail[i].email,
|
||||
receiver_phone: contactMail[i]?.phone || '',
|
||||
expiry_date: localExpireDate,
|
||||
company_name: orgName,
|
||||
signing_url: signPdf,
|
||||
};
|
||||
if (email_subject && email_body) {
|
||||
replaceVar = replaceMailVaribles(email_subject, email_body, variables);
|
||||
} else if (email_subject) {
|
||||
replaceVar = replaceMailVaribles(email_subject, '', variables);
|
||||
replaceVar = { subject: replaceVar.subject, body: email_html };
|
||||
} else if (email_body) {
|
||||
replaceVar = replaceMailVaribles(
|
||||
`${template.ExtUserPtr.Name} has requested you to sign "${template.Name}"`,
|
||||
email_body,
|
||||
variables
|
||||
);
|
||||
} else {
|
||||
replaceVar = {
|
||||
subject: `${template.ExtUserPtr.Name} has requested you to sign "${template.Name}"`,
|
||||
body: email_html,
|
||||
};
|
||||
}
|
||||
|
||||
const subject = replaceVar.subject;
|
||||
const html = replaceVar.body;
|
||||
let params = {
|
||||
recipient: contactMail[i].email,
|
||||
subject: subject,
|
||||
from: sender,
|
||||
html: html,
|
||||
extUserId: template.ExtUserPtr.objectId,
|
||||
mailProvider: template?.ExtUserPtr?.active_mail_adapter || '',
|
||||
};
|
||||
sendMail = await axios.post(url, params, { headers: headers });
|
||||
} catch (error) {
|
||||
console.log('error', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (sendMail.data.result.status === 'success') {
|
||||
try {
|
||||
const doc = {
|
||||
objectId: res.id,
|
||||
file: template?.URL,
|
||||
name: template?.Name,
|
||||
note: template?.Note || '',
|
||||
description: template?.Description || '',
|
||||
signers: contact?.map(x => ({
|
||||
name: x.name,
|
||||
email: x.email,
|
||||
phone: x?.phone || '',
|
||||
})),
|
||||
createdAt: res.createdAt,
|
||||
};
|
||||
if (template.ExtUserPtr && template.ExtUserPtr?.Webhook) {
|
||||
sendDoctoWebhook(doc, template.ExtUserPtr?.Webhook, userPtr?.objectId);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Err', err);
|
||||
}
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_document_with_templateid',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
|
||||
const subscriptionCls = new Parse.Object('contracts_Subscriptions');
|
||||
subscriptionCls.id = resSub.id;
|
||||
if (allowedCredits > 0) {
|
||||
const updateAllowedcredits = allowedCredits - 1 || 0;
|
||||
subscriptionCls.set('AllowedCredits', updateAllowedcredits);
|
||||
} else {
|
||||
const updateAddonCredits = addonCredits > 0 ? addonCredits - 1 : 0;
|
||||
subscriptionCls.set('AddonCredits', updateAddonCredits);
|
||||
}
|
||||
const resSubcription = await subscriptionCls.save(null, { useMasterKey: true });
|
||||
// console.log("resSubcription ", resSubcription)
|
||||
return response.json({
|
||||
objectId: res.id,
|
||||
signurl: contact.map(x => ({
|
||||
email: x.email,
|
||||
url: `${baseUrl.origin}/login/${btoa(
|
||||
`${res.id}/${x.email}/${x.contactPtr.objectId}`
|
||||
)}`,
|
||||
})),
|
||||
message: 'Document sent successfully!',
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_document_with_templateid',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response.status(400).json({ error: 'Please provide signers properly!' });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_document_with_templateid',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response.status(400).json({ error: 'Please setup template properly!' });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_document_with_templateid',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Invalid template id!' });
|
||||
}
|
||||
} else {
|
||||
return response
|
||||
.status(429)
|
||||
.json({ error: 'Quota reached, Please buy credits and try again later.' });
|
||||
}
|
||||
} else {
|
||||
return response.status(400).json({
|
||||
error: 'Please purchase or renew your subscription.',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
if (err.code === 101) {
|
||||
return response.status(404).json({ error: 'Invalid template id!' });
|
||||
}
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
export default async function createContact(request, response) {
|
||||
const name = request.body.name;
|
||||
const phone = request.body?.phone;
|
||||
const email = request.body.email;
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
try {
|
||||
const contactbook = new Parse.Query('contracts_Contactbook');
|
||||
contactbook.equalTo('Email', email);
|
||||
contactbook.equalTo('CreatedBy', userPtr);
|
||||
contactbook.notEqualTo('IsDeleted', true);
|
||||
const userExists = await contactbook.first({ useMasterKey: true });
|
||||
|
||||
if (userExists) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_contact',
|
||||
properties: { response_code: 401 },
|
||||
});
|
||||
}
|
||||
return response
|
||||
.status(401)
|
||||
.json({ error: 'Contact already exists!', objectId: userExists.id });
|
||||
} else {
|
||||
try {
|
||||
const Tenant = new Parse.Query('partners_Tenant');
|
||||
Tenant.equalTo('UserId', userPtr);
|
||||
const tenantRes = await Tenant.first({ useMasterKey: true });
|
||||
|
||||
const contactQuery = new Parse.Object('contracts_Contactbook');
|
||||
contactQuery.set('Name', name);
|
||||
if (phone) {
|
||||
contactQuery.set('Phone', phone);
|
||||
}
|
||||
contactQuery.set('Email', email);
|
||||
contactQuery.set('UserRole', 'contracts_Guest');
|
||||
if (tenantRes && tenantRes.id) {
|
||||
contactQuery.set('TenantId', {
|
||||
__type: 'Pointer',
|
||||
className: 'partners_Tenant',
|
||||
objectId: tenantRes.id,
|
||||
});
|
||||
}
|
||||
try {
|
||||
const _users = Parse.Object.extend('User');
|
||||
const _user = new _users();
|
||||
_user.set('name', name);
|
||||
_user.set('username', email);
|
||||
_user.set('email', email);
|
||||
_user.set('password', email);
|
||||
if (phone) {
|
||||
_user.set('phone', phone);
|
||||
}
|
||||
|
||||
const user = await _user.save();
|
||||
if (user) {
|
||||
const currentUser = userPtr;
|
||||
contactQuery.set('CreatedBy', currentUser);
|
||||
contactQuery.set('UserId', user);
|
||||
|
||||
const acl = new Parse.ACL();
|
||||
acl.setReadAccess(userPtr.objectId, true);
|
||||
acl.setWriteAccess(userPtr.objectId, true);
|
||||
acl.setReadAccess(user.id, true);
|
||||
acl.setWriteAccess(user.id, true);
|
||||
contactQuery.setACL(acl);
|
||||
|
||||
const contactRes = await contactQuery.save();
|
||||
const parseRes = JSON.parse(JSON.stringify(contactRes));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_contact',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: parseRes.objectId,
|
||||
name: parseRes.Name,
|
||||
email: parseRes.Email,
|
||||
phone: parseRes?.Phone || '',
|
||||
createdAt: parseRes.createdAt,
|
||||
updatedAt: parseRes.updatedAt,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err in', err);
|
||||
if (err.code === 202) {
|
||||
const params = { email: email };
|
||||
const userRes = await Parse.Cloud.run('getUserId', params);
|
||||
contactQuery.set('CreatedBy', userPtr);
|
||||
contactQuery.set('UserId', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: userRes.id,
|
||||
});
|
||||
const acl = new Parse.ACL();
|
||||
acl.setReadAccess(userPtr.objectId, true);
|
||||
acl.setWriteAccess(userPtr.objectId, true);
|
||||
acl.setReadAccess(userRes.id, true);
|
||||
acl.setWriteAccess(userRes.id, true);
|
||||
|
||||
contactQuery.setACL(acl);
|
||||
const contactRes = await contactQuery.save();
|
||||
if (contactRes) {
|
||||
const parseRes = JSON.parse(JSON.stringify(contactRes));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_contact',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: parseRes.objectId,
|
||||
name: parseRes.Name,
|
||||
email: parseRes.Email,
|
||||
phone: parseRes?.Phone || '',
|
||||
createdAt: parseRes.createdAt,
|
||||
updatedAt: parseRes.updatedAt,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (err.code === 137) {
|
||||
return response.status(401).json({ error: 'Contact already exists!' });
|
||||
}
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
if (err.code === 137) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_contact',
|
||||
properties: { response_code: 401 },
|
||||
});
|
||||
}
|
||||
return response.status(401).json({ error: 'Contact already exists!' });
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_contact',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_contact',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,454 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import {
|
||||
color,
|
||||
customAPIurl,
|
||||
replaceMailVaribles,
|
||||
saveFileUsage,
|
||||
formatWidgetOptions,
|
||||
sanitizeFileName,
|
||||
cloudServerUrl,
|
||||
} from '../../../../Utils.js';
|
||||
import uploadFileToS3 from '../../../parsefunction/uploadFiletoS3.js';
|
||||
|
||||
// `sendDoctoWebhook` is used to send res data of document on webhook
|
||||
async function sendDoctoWebhook(doc, WebhookUrl, userId) {
|
||||
if (WebhookUrl) {
|
||||
const params = { event: 'created', ...doc };
|
||||
|
||||
await axios
|
||||
.post(WebhookUrl, params, { headers: { 'Content-Type': 'application/json' } })
|
||||
.then(res => {
|
||||
try {
|
||||
// console.log('res ', res);
|
||||
const webhook = new Parse.Object('contracts_Webhook');
|
||||
webhook.set('Log', res?.status);
|
||||
webhook.set('UserId', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: userId,
|
||||
});
|
||||
webhook.save(null, { useMasterKey: true });
|
||||
} catch (err) {
|
||||
console.log('err save in contracts_Webhook', err);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.log('Err send data to webhook', err?.message);
|
||||
try {
|
||||
const webhook = new Parse.Object('contracts_Webhook');
|
||||
webhook.set('Log', err?.status);
|
||||
webhook.set('UserId', {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: userId,
|
||||
});
|
||||
webhook.save(null, { useMasterKey: true });
|
||||
} catch (err) {
|
||||
console.log('err save in contracts_Webhook', err?.message);
|
||||
}
|
||||
});
|
||||
// console.log('res ', res.data);
|
||||
}
|
||||
}
|
||||
const randomId = () => Math.floor(1000 + Math.random() * 9000);
|
||||
export default async function createDocumentwithCoordinate(request, response) {
|
||||
const name = request.body.title;
|
||||
const note = request.body.note;
|
||||
const description = request.body.description;
|
||||
const send_email = request.body.send_email;
|
||||
const signers = request.body.signers;
|
||||
const folderId = request.body.folderId;
|
||||
const base64File = request.body.file;
|
||||
const fileData = request.files?.[0] ? request.files[0].buffer : null;
|
||||
const email_subject = request.body.email_subject;
|
||||
const email_body = request.body.email_body;
|
||||
const sendInOrder = request.body.sendInOrder || true;
|
||||
const TimeToCompleteDays = request.body.timeToCompleteDays || 15;
|
||||
const IsEnableOTP = request.body?.enableOTP === true ? true : false;
|
||||
const isTourEnabled = request.body?.enableTour || false;
|
||||
// console.log('fileData ', fileData);
|
||||
const protocol = customAPIurl();
|
||||
const baseUrl = new URL(process.env.PUBLIC_URL);
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const extUsers = new Parse.Query('contracts_Users');
|
||||
extUsers.equalTo('UserId', userPtr);
|
||||
extUsers.include('TenantId');
|
||||
const extUser = await extUsers.first({ useMasterKey: true });
|
||||
|
||||
const subscription = new Parse.Query('contracts_Subscriptions');
|
||||
subscription.equalTo('TenantId', {
|
||||
__type: 'Pointer',
|
||||
className: 'partners_Tenant',
|
||||
objectId: extUser.get('TenantId').id,
|
||||
});
|
||||
subscription.include('ExtUserPtr');
|
||||
subscription.greaterThanOrEqualTo('Next_billing_date', new Date());
|
||||
const resSub = await subscription.first({ useMasterKey: true });
|
||||
if (resSub) {
|
||||
const _resSub = JSON.parse(JSON.stringify(resSub));
|
||||
const allowedCredits = _resSub?.AllowedCredits || 0;
|
||||
const addonCredits = _resSub?.AddonCredits || 0;
|
||||
const totalcredits = allowedCredits + addonCredits;
|
||||
if (totalcredits > 0) {
|
||||
if (signers && signers.length > 0) {
|
||||
// Check if at least one signature exists among all items in the signers array
|
||||
let isSignExist = signers.every(item =>
|
||||
item.widgets.some(data => data?.type === 'signature')
|
||||
);
|
||||
if (!isSignExist) {
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'Please add at least one signature widget for all signers' });
|
||||
}
|
||||
const parseExtUser = JSON.parse(JSON.stringify(extUser));
|
||||
let fileUrl;
|
||||
if (request.files?.[0]) {
|
||||
const base64 = fileData?.toString('base64');
|
||||
const file = new Parse.File(request.files?.[0]?.originalname, {
|
||||
base64: base64,
|
||||
});
|
||||
await file.save({ useMasterKey: true });
|
||||
fileUrl = file.url();
|
||||
const buffer = Buffer.from(base64, 'base64');
|
||||
saveFileUsage(buffer.length, fileUrl, parseUser.userId.objectId);
|
||||
} else {
|
||||
const filename = sanitizeFileName(`${name}.pdf`);
|
||||
let adapter = {};
|
||||
const ActiveFileAdapter = parseExtUser?.TenantId?.ActiveFileAdapter || '';
|
||||
if (ActiveFileAdapter) {
|
||||
adapter =
|
||||
parseExtUser?.TenantId?.FileAdapters?.find(x => (x.id = ActiveFileAdapter)) || {};
|
||||
}
|
||||
if (adapter?.id) {
|
||||
const filedata = Buffer.from(base64File, 'base64');
|
||||
// `uploadFileToS3` is used to save document in user's file storage
|
||||
fileUrl = await uploadFileToS3(filedata, filename, 'application/pdf', adapter);
|
||||
} else {
|
||||
const file = new Parse.File(filename, { base64: base64File }, 'application/pdf');
|
||||
await file.save({ useMasterKey: true });
|
||||
fileUrl = file.url();
|
||||
}
|
||||
const buffer = Buffer.from(base64File, 'base64');
|
||||
saveFileUsage(buffer.length, fileUrl, parseUser.userId.objectId);
|
||||
}
|
||||
const extUserPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Users',
|
||||
objectId: extUser.id,
|
||||
};
|
||||
const object = new Parse.Object('contracts_Document');
|
||||
object.set('Name', name);
|
||||
|
||||
if (note) {
|
||||
object.set('Note', note);
|
||||
}
|
||||
if (description) {
|
||||
object.set('Description', description);
|
||||
}
|
||||
if (sendInOrder) {
|
||||
object.set('SendinOrder', sendInOrder);
|
||||
}
|
||||
object.set('URL', fileUrl);
|
||||
object.set('SignedUrl', fileUrl);
|
||||
object.set('SentToOthers', true);
|
||||
object.set('CreatedBy', userPtr);
|
||||
object.set('ExtUserPtr', extUserPtr);
|
||||
if (TimeToCompleteDays) {
|
||||
object.set('TimeToCompleteDays', TimeToCompleteDays);
|
||||
}
|
||||
object.set('IsEnableOTP', IsEnableOTP);
|
||||
object.set('IsTourEnabled', isTourEnabled);
|
||||
object.set('IsSendMail', send_email);
|
||||
if (parseExtUser?.TenantId?.ActiveFileAdapter) {
|
||||
object.set('FileAdapterId', parseExtUser?.TenantId?.ActiveFileAdapter);
|
||||
}
|
||||
let contact = [];
|
||||
if (signers && signers.length > 0) {
|
||||
let parseSigners;
|
||||
if (base64File) {
|
||||
parseSigners = signers;
|
||||
} else {
|
||||
parseSigners = JSON.parse(signers);
|
||||
}
|
||||
let createContactUrl = protocol + '/v1/createcontact';
|
||||
|
||||
for (const [index, element] of parseSigners.entries()) {
|
||||
const body = {
|
||||
name: element?.name || '',
|
||||
email: element?.email || '',
|
||||
phone: element?.phone || '',
|
||||
};
|
||||
try {
|
||||
const res = await axios.post(createContactUrl, body, {
|
||||
headers: { 'Content-Type': 'application/json', 'x-api-token': reqToken },
|
||||
});
|
||||
// console.log('res ', res.data);
|
||||
const contactPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Contactbook',
|
||||
objectId: res.data?.objectId,
|
||||
};
|
||||
const newObj = { ...element, contactPtr: contactPtr, index: index };
|
||||
contact.push(newObj);
|
||||
} catch (err) {
|
||||
// console.log('err ', err.response);
|
||||
if (err?.response?.data?.objectId) {
|
||||
const contactPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Contactbook',
|
||||
objectId: err.response.data?.objectId,
|
||||
};
|
||||
const newObj = { ...element, contactPtr: contactPtr, index: index };
|
||||
contact.push(newObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
object.set(
|
||||
'Signers',
|
||||
contact?.map(x => x.contactPtr)
|
||||
);
|
||||
let updatePlaceholders = contact.map(signer => {
|
||||
const placeHolder = [];
|
||||
|
||||
for (const widget of signer.widgets) {
|
||||
const pageNumber = widget.page;
|
||||
const options = formatWidgetOptions(widget.type, widget.options);
|
||||
const page = placeHolder.find(page => page.pageNumber === pageNumber);
|
||||
const widgetData = {
|
||||
isStamp: widget.type === 'stamp' || widget.type === 'image',
|
||||
key: randomId(),
|
||||
isDrag: false,
|
||||
scale: 1,
|
||||
isMobile: false,
|
||||
zIndex: 1,
|
||||
type: widget.type === 'textbox' ? 'text input' : widget.type,
|
||||
options: options,
|
||||
Width: widget.w,
|
||||
Height: widget.h,
|
||||
xPosition: widget.x,
|
||||
yPosition: widget.y,
|
||||
};
|
||||
|
||||
if (page) {
|
||||
page.pos.push(widgetData);
|
||||
} else {
|
||||
placeHolder.push({ pageNumber, pos: [widgetData] });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
signerObjId: signer?.contactPtr?.objectId,
|
||||
signerPtr: signer?.contactPtr,
|
||||
Role: signer.role,
|
||||
Id: randomId(),
|
||||
blockColor: color[signer?.index],
|
||||
placeHolder,
|
||||
};
|
||||
});
|
||||
object.set('Placeholders', updatePlaceholders);
|
||||
}
|
||||
if (folderId) {
|
||||
object.set('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Document',
|
||||
objectId: folderId,
|
||||
});
|
||||
}
|
||||
const newACL = new Parse.ACL();
|
||||
newACL.setPublicReadAccess(false);
|
||||
newACL.setPublicWriteAccess(false);
|
||||
newACL.setReadAccess(userPtr.objectId, true);
|
||||
newACL.setWriteAccess(userPtr.objectId, true);
|
||||
object.setACL(newACL);
|
||||
const res = await object.save(null, { useMasterKey: true });
|
||||
const doc = {
|
||||
objectId: res.id,
|
||||
file: fileUrl,
|
||||
name: name,
|
||||
note: note || '',
|
||||
description: description || '',
|
||||
signers: contact?.map(x => ({ name: x.name, email: x.email, phone: x?.phone || '' })),
|
||||
createdAt: res.createdAt,
|
||||
};
|
||||
if (parseExtUser && parseExtUser.Webhook) {
|
||||
sendDoctoWebhook(doc, parseExtUser?.Webhook, userPtr?.objectId);
|
||||
}
|
||||
const newDate = new Date();
|
||||
newDate.setDate(newDate.getDate() + 15);
|
||||
const localExpireDate = newDate.toLocaleDateString('en-US', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
});
|
||||
let sender = parseExtUser.Email;
|
||||
if (send_email === false) {
|
||||
console.log("don't send mail");
|
||||
} else {
|
||||
let contactMail = contact;
|
||||
if (sendInOrder) {
|
||||
contactMail = contact.slice();
|
||||
contactMail.splice(1);
|
||||
}
|
||||
for (let i = 0; i < contactMail.length; i++) {
|
||||
try {
|
||||
const imgPng = 'https://qikinnovation.ams3.digitaloceanspaces.com/logo.png';
|
||||
let url = `${cloudServerUrl}/functions/sendmailv3/`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': process.env.APP_ID,
|
||||
'X-Parse-Master-Key': process.env.MASTER_KEY,
|
||||
};
|
||||
|
||||
const objectId = contactMail[i].contactPtr.objectId;
|
||||
const hostUrl = baseUrl.origin;
|
||||
//encode this url value `${response.id}/${contactMail[i].email}/${objectId}` to base64 using `btoa` function
|
||||
const encodeBase64 = btoa(`${res.id}/${contactMail[i].email}/${objectId}`);
|
||||
let signPdf = `${hostUrl}/login/${encodeBase64}`;
|
||||
const openSignUrl = 'https://www.opensignlabs.com/contact-us';
|
||||
const orgName = parseExtUser.Company ? parseExtUser.Company : '';
|
||||
const themeBGcolor = '#47a3ad';
|
||||
const email_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: white;padding-bottom: 20px;'> <div style='padding:10px 10px 0 10px'><img src=" +
|
||||
imgPng +
|
||||
" height='50' style='padding:20px; width:170px; height:40px;' /></div> <div style='padding:2px; font-family: system-ui;background-color:" +
|
||||
themeBGcolor +
|
||||
";'><p style='font-size: 20px;font-weight: 400;color: white;padding-left: 20px;' > Digital Signature Request</p></div><div><p style='padding: 20px;font-family: system-ui;font-size: 14px; margin-bottom: 10px;'> " +
|
||||
parseExtUser.Name +
|
||||
' has requested you to review and sign <strong> ' +
|
||||
name +
|
||||
"</strong>.</p><div style='padding: 5px 0px 5px 25px;display: flex;flex-direction: row;justify-content: space-around;'><table> <tr> <td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Sender</td> <td> </td> <td style='color:#626363;font-weight:bold'>" +
|
||||
sender +
|
||||
"</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Organization</td> <td> </td><td style='color:#626363;font-weight:bold'> " +
|
||||
orgName +
|
||||
"</td></tr> <tr> <td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Expires on</td><td> </td> <td style='color:#626363;font-weight:bold'>" +
|
||||
localExpireDate +
|
||||
"</td></tr><tr> <td></td> <td> </td></tr></table> </div> <div style='margin-left:70px'><a target=_blank href=" +
|
||||
signPdf +
|
||||
"> <button style='padding: 12px 12px 12px 12px;background-color: #d46b0f;color: white; border: 0px;box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px,rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;font-weight:bold;margin-top:30px'>Sign here</button></a> </div> <div style='display: flex; justify-content: center;margin-top: 10px;'> </div></div></div><div><p> This is an automated email from OpenSign™. For any queries regarding this email, please contact the sender " +
|
||||
sender +
|
||||
' directly.If you think this email is inappropriate or spam, you may file a complaint with OpenSign™ <a href=' +
|
||||
openSignUrl +
|
||||
' target=_blank>here</a>.</p> </div></div></body> </html>';
|
||||
let replaceVar;
|
||||
const variables = {
|
||||
document_title: name,
|
||||
sender_name: parseExtUser.Name,
|
||||
sender_mail: parseExtUser.Email,
|
||||
sender_phone: parseExtUser?.Phone || '',
|
||||
receiver_name: contactMail[i].name,
|
||||
receiver_email: contactMail[i].email,
|
||||
receiver_phone: contactMail[i]?.phone || '',
|
||||
expiry_date: localExpireDate,
|
||||
company_name: orgName,
|
||||
signing_url: signPdf,
|
||||
};
|
||||
if (email_subject && email_body) {
|
||||
replaceVar = replaceMailVaribles(email_subject, email_body, variables);
|
||||
} else if (email_subject) {
|
||||
replaceVar = replaceMailVaribles(email_subject, '', variables);
|
||||
replaceVar = { subject: replaceVar.subject, body: email_html };
|
||||
} else if (email_body) {
|
||||
replaceVar = replaceMailVaribles(
|
||||
`${parseExtUser.Name} has requested you to sign "${name}"`,
|
||||
email_body,
|
||||
variables
|
||||
);
|
||||
} else {
|
||||
replaceVar = {
|
||||
subject: `${parseExtUser.Name} has requested you to sign "${name}"`,
|
||||
body: email_html,
|
||||
};
|
||||
}
|
||||
const subject = replaceVar.subject;
|
||||
const html = replaceVar.body;
|
||||
|
||||
let params = {
|
||||
recipient: contactMail[i].email,
|
||||
subject: subject,
|
||||
from: sender,
|
||||
html: html,
|
||||
extUserId: extUser.id,
|
||||
mailProvider: parseExtUser?.active_mail_adapter || '',
|
||||
};
|
||||
|
||||
await axios.post(url, params, { headers: headers });
|
||||
} catch (error) {
|
||||
console.log('error', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (sendMail.data.result.status === 'success') {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_document',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
|
||||
const subscriptionCls = new Parse.Object('contracts_Subscriptions');
|
||||
subscriptionCls.id = resSub.id;
|
||||
if (allowedCredits > 0) {
|
||||
const updateAllowedcredits = allowedCredits - 1 || 0;
|
||||
subscriptionCls.set('AllowedCredits', updateAllowedcredits);
|
||||
} else {
|
||||
const updateAddonCredits = addonCredits > 0 ? addonCredits - 1 : 0;
|
||||
subscriptionCls.set('AddonCredits', updateAddonCredits);
|
||||
}
|
||||
const resSubcription = await subscriptionCls.save(null, { useMasterKey: true });
|
||||
// console.log('resSubcription ', resSubcription);
|
||||
return response.json({
|
||||
objectId: res.id,
|
||||
signurl: contact.map(x => ({
|
||||
email: x.email,
|
||||
url: `${baseUrl.origin}/login/${btoa(
|
||||
`${res.id}/${x.email}/${x.contactPtr.objectId}`
|
||||
)}`,
|
||||
})),
|
||||
message: 'Document sent successfully!',
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_document',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response.status(400).json({ error: 'Please provide signers!' });
|
||||
}
|
||||
} else {
|
||||
return response
|
||||
.status(429)
|
||||
.json({ error: 'Quota reached, Please buy credits and try again later.' });
|
||||
}
|
||||
} else {
|
||||
return response.status(400).json({
|
||||
error: 'Please purchase or renew your subscription.',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
export default async function createFolder(request, response) {
|
||||
const apiToken = request.headers['x-api-token'];
|
||||
const folderName = request.body.folderName;
|
||||
const parentFolderId = request.body.parentFolderId;
|
||||
if (!apiToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', apiToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const userQuery = new Parse.Query('contracts_Users');
|
||||
userQuery.equalTo('UserId', userPtr);
|
||||
const extUser = await userQuery.first({ useMasterKey: true });
|
||||
|
||||
const folderCls = new Parse.Object('contracts_Document');
|
||||
folderCls.set('Name', folderName);
|
||||
folderCls.set('CreatedBy', userPtr);
|
||||
folderCls.set('Type', 'Folder');
|
||||
folderCls.set('ExtUserPtr', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Users',
|
||||
objectId: extUser.id,
|
||||
});
|
||||
if (parentFolderId) {
|
||||
folderCls.set('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Document',
|
||||
objectId: parentFolderId,
|
||||
});
|
||||
}
|
||||
const acl = new Parse.ACL();
|
||||
acl.setReadAccess(parseUser.userId.objectId, true); // Allow read access to the userPtr
|
||||
acl.setWriteAccess(parseUser.userId.objectId, true); // Allow write access to the userPtr
|
||||
|
||||
// Set the ACL to the document
|
||||
folderCls.setACL(acl);
|
||||
|
||||
const _resFolder = await folderCls.save(null, { useMasterKey: true });
|
||||
if (_resFolder) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_folder',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
const parseRes = JSON.parse(JSON.stringify(_resFolder));
|
||||
return response.json({
|
||||
objectId: parseRes.objectId,
|
||||
folderName: parseRes.Name,
|
||||
parentFolderId: parseRes?.Folder?.objectId || '',
|
||||
createdAt: parseRes.createdAt,
|
||||
updatedAt: parseRes.updatedAt,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import {
|
||||
color,
|
||||
customAPIurl,
|
||||
saveFileUsage,
|
||||
formatWidgetOptions,
|
||||
sanitizeFileName,
|
||||
} from '../../../../Utils.js';
|
||||
import uploadFileToS3 from '../../../parsefunction/uploadFiletoS3.js';
|
||||
|
||||
const randomId = () => Math.floor(1000 + Math.random() * 9000);
|
||||
export default async function createTemplatewithCoordinate(request, response) {
|
||||
const name = request.body.title;
|
||||
const note = request.body.note;
|
||||
const description = request.body.description;
|
||||
const signers = request.body.signers;
|
||||
const folderId = request.body.folderId;
|
||||
const base64File = request.body.file;
|
||||
const fileData = request.files?.[0] ? request.files[0].buffer : null;
|
||||
const SendinOrder = request.body.sendInOrder || true;
|
||||
const isEnableOTP = request.body?.enableOTP === true ? true : false;
|
||||
const isTourEnabled = request.body?.enableTour || false;
|
||||
|
||||
// console.log('fileData ', fileData);
|
||||
const protocol = customAPIurl();
|
||||
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
if (signers && signers.length > 0) {
|
||||
const contractsUser = new Parse.Query('contracts_Users');
|
||||
contractsUser.equalTo('UserId', userPtr);
|
||||
contractsUser.include('TenantId');
|
||||
const extUser = await contractsUser.first({ useMasterKey: true });
|
||||
const parseExtUser = JSON.parse(JSON.stringify(extUser));
|
||||
let fileUrl;
|
||||
if (request.files?.[0]) {
|
||||
const base64 = fileData?.toString('base64');
|
||||
const file = new Parse.File(request.files?.[0]?.originalname, {
|
||||
base64: base64,
|
||||
});
|
||||
await file.save({ useMasterKey: true });
|
||||
fileUrl = file.url();
|
||||
const buffer = Buffer.from(base64, 'base64');
|
||||
saveFileUsage(buffer.length, fileUrl, parseUser.userId.objectId);
|
||||
} else {
|
||||
const filename = sanitizeFileName(`${name}.pdf`);
|
||||
let adapter = {};
|
||||
const ActiveFileAdapter = parseExtUser?.TenantId?.ActiveFileAdapter || '';
|
||||
if (ActiveFileAdapter) {
|
||||
adapter =
|
||||
parseExtUser?.TenantId?.FileAdapters?.find(x => (x.id = ActiveFileAdapter)) || {};
|
||||
}
|
||||
if (adapter?.id) {
|
||||
const filedata = Buffer.from(base64File, 'base64');
|
||||
// `uploadFileToS3` is used to save document in user's file storage
|
||||
fileUrl = await uploadFileToS3(filedata, filename, 'application/pdf', adapter);
|
||||
} else {
|
||||
const file = new Parse.File(filename, { base64: base64File }, 'application/pdf');
|
||||
await file.save({ useMasterKey: true });
|
||||
fileUrl = file.url();
|
||||
}
|
||||
const buffer = Buffer.from(base64File, 'base64');
|
||||
saveFileUsage(buffer.length, fileUrl, parseUser.userId.objectId);
|
||||
}
|
||||
const extUserPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Users',
|
||||
objectId: extUser.id,
|
||||
};
|
||||
const object = new Parse.Object('contracts_Template');
|
||||
object.set('Name', name);
|
||||
if (note) {
|
||||
object.set('Note', note);
|
||||
}
|
||||
if (description) {
|
||||
object.set('Description', description);
|
||||
}
|
||||
if (SendinOrder) {
|
||||
object.set('SendinOrder', SendinOrder);
|
||||
}
|
||||
object.set('URL', fileUrl);
|
||||
object.set('CreatedBy', userPtr);
|
||||
object.set('ExtUserPtr', extUserPtr);
|
||||
object.set('IsEnableOTP', isEnableOTP);
|
||||
object.set('IsTourEnabled', isTourEnabled);
|
||||
let contact = [];
|
||||
if (signers && signers.length > 0) {
|
||||
let parseSigners;
|
||||
if (base64File) {
|
||||
parseSigners = signers;
|
||||
} else {
|
||||
parseSigners = JSON.parse(signers);
|
||||
}
|
||||
let createContactUrl = protocol + '/v1/createcontact';
|
||||
|
||||
for (const [index, element] of parseSigners.entries()) {
|
||||
if (element?.name && element?.email) {
|
||||
const body = {
|
||||
name: element?.name || '',
|
||||
email: element?.email || '',
|
||||
phone: element?.phone || '',
|
||||
};
|
||||
try {
|
||||
const res = await axios.post(createContactUrl, body, {
|
||||
headers: { 'Content-Type': 'application/json', 'x-api-token': reqToken },
|
||||
});
|
||||
// console.log('res ', res.data);
|
||||
const contactPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Contactbook',
|
||||
objectId: res.data?.objectId,
|
||||
};
|
||||
const newObj = { ...element, contactPtr: contactPtr, index: index };
|
||||
contact.push(newObj);
|
||||
} catch (err) {
|
||||
// console.log('err ', err.response);
|
||||
if (err?.response?.data?.objectId) {
|
||||
const contactPtr = {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Contactbook',
|
||||
objectId: err.response.data?.objectId,
|
||||
};
|
||||
const newObj = { ...element, contactPtr: contactPtr, index: index };
|
||||
contact.push(newObj);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const newObj = { ...element, contactPtr: {}, index: index };
|
||||
contact.push(newObj);
|
||||
}
|
||||
}
|
||||
const updatedSigners = contact?.filter(x => x.contactPtr && x.contactPtr.objectId);
|
||||
if (updatedSigners && updatedSigners.length > 0) {
|
||||
object.set(
|
||||
'Signers',
|
||||
updatedSigners?.map(x => x.contactPtr)
|
||||
);
|
||||
}
|
||||
let updatePlaceholders = contact.map((signer, index) => {
|
||||
const placeHolder = [];
|
||||
|
||||
for (const widget of signer.widgets) {
|
||||
const pageNumber = widget.page;
|
||||
const page = placeHolder.find(page => page.pageNumber === pageNumber);
|
||||
const options = formatWidgetOptions(widget.type, widget.options);
|
||||
const widgetData = {
|
||||
isStamp: widget.type === 'stamp' || widget.type === 'image',
|
||||
key: randomId(),
|
||||
isDrag: false,
|
||||
scale: 1,
|
||||
isMobile: false,
|
||||
zIndex: 1,
|
||||
type: widget.type === 'textbox' ? 'text input' : widget.type,
|
||||
options: options,
|
||||
Width: widget.w,
|
||||
Height: widget.h,
|
||||
xPosition: widget.x,
|
||||
yPosition: widget.y,
|
||||
};
|
||||
|
||||
if (page) {
|
||||
page.pos.push(widgetData);
|
||||
} else {
|
||||
placeHolder.push({
|
||||
pageNumber,
|
||||
pos: [widgetData],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
signerObjId: signer?.contactPtr?.objectId,
|
||||
signerPtr: signer?.contactPtr,
|
||||
Role: signer.role,
|
||||
Id: randomId(),
|
||||
blockColor: color[signer?.index],
|
||||
placeHolder,
|
||||
};
|
||||
});
|
||||
object.set('Placeholders', updatePlaceholders);
|
||||
}
|
||||
if (folderId) {
|
||||
object.set('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Template',
|
||||
objectId: folderId,
|
||||
});
|
||||
}
|
||||
if (parseExtUser?.TenantId?.ActiveFileAdapter) {
|
||||
object.set('FileAdapterId', parseExtUser?.TenantId?.ActiveFileAdapter);
|
||||
}
|
||||
const newACL = new Parse.ACL();
|
||||
newACL.setPublicReadAccess(false);
|
||||
newACL.setPublicWriteAccess(false);
|
||||
newACL.setReadAccess(userPtr.objectId, true);
|
||||
newACL.setWriteAccess(userPtr.objectId, true);
|
||||
object.setACL(newACL);
|
||||
const res = await object.save(null, { useMasterKey: true });
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_template',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: res.id,
|
||||
message: 'Template created successfully!',
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_create_template',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response.status(400).json({ error: 'Please provide signers!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
export default async function deleteContact(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const Contactbook = new Parse.Query('contracts_Contactbook');
|
||||
Contactbook.equalTo('objectId', request.params.contact_id);
|
||||
Contactbook.equalTo('CreatedBy', userPtr);
|
||||
const res = await Contactbook.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const isDeleted = res.get('IsDeleted');
|
||||
if (isDeleted && isDeleted) {
|
||||
return response.status(404).json({ error: 'Contact not found!' });
|
||||
} else {
|
||||
const Contactbook = Parse.Object.extend('contracts_Contactbook');
|
||||
const deleteQuery = new Contactbook();
|
||||
deleteQuery.id = request.params.contact_id;
|
||||
deleteQuery.set('IsDeleted', true);
|
||||
const deleteRes = await deleteQuery.save(null, { useMasterKey: true });
|
||||
if (deleteRes) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_contact',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: request.params.contact_id,
|
||||
deletedAt: deleteRes.get('updatedAt'),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_contact',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Contact not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
export default async function deleteDocument(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const Document = new Parse.Query('contracts_Document');
|
||||
Document.equalTo('objectId', request.params.document_id);
|
||||
Document.equalTo('CreatedBy', userPtr);
|
||||
Document.include('ExtUserPtr.TenantId');
|
||||
const res = await Document.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const isArchive = res.get('IsArchive');
|
||||
if (isArchive && isArchive) {
|
||||
return response.status(404).json({ error: 'Document not found!' });
|
||||
} else {
|
||||
const Document = Parse.Object.extend('contracts_Document');
|
||||
const deleteQuery = new Document();
|
||||
deleteQuery.id = request.params.document_id;
|
||||
deleteQuery.set('IsArchive', true);
|
||||
const deleteRes = await deleteQuery.save(null, { useMasterKey: true });
|
||||
if (deleteRes) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_document',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: request.params.document_id,
|
||||
deletedAt: deleteRes.get('updatedAt'),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_document',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Document not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
export default async function deleteFolder(request, response) {
|
||||
const apiToken = request.headers['x-api-token'];
|
||||
const folderId = request.params.folder_id;
|
||||
if (!apiToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', apiToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const obj = new Parse.Query('contracts_Document');
|
||||
obj.equalTo('objectId', folderId);
|
||||
obj.equalTo('IsArchive', true);
|
||||
obj.equalTo('CreatedBy', userPtr);
|
||||
obj.include('ExtUserPtr.TenantId');
|
||||
const isFolderDeleted = await obj.first({ useMasterKey: true });
|
||||
if (!isFolderDeleted) {
|
||||
const folder = new Parse.Query('contracts_Document');
|
||||
folder.equalTo('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Document',
|
||||
objectId: folderId,
|
||||
});
|
||||
|
||||
folder.notEqualTo('IsArchive', true);
|
||||
folder.equalTo('CreatedBy', userPtr);
|
||||
folder.equalTo('Type', 'Folder');
|
||||
folder.include('ExtUserPtr.TenantId');
|
||||
const isSubItems = await folder.first({ useMasterKey: true });
|
||||
// console.log('isSubItems ', isSubItems);
|
||||
if (isSubItems) {
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'folder is not empty, contains document or folder.' });
|
||||
} else {
|
||||
const deleteFolder = new Parse.Object('contracts_Document');
|
||||
deleteFolder.id = folderId;
|
||||
deleteFolder.set('IsArchive', true);
|
||||
const deleteRes = await deleteFolder.save(null, { useMasterKey: true });
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_folder',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({ objectId: deleteRes.id, deletedAt: deleteRes.updatedAt });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_folder',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'folder not found.' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err is delete folder API', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
export default async function deletedTemplate(request, response) {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const template = new Parse.Query('contracts_Template');
|
||||
template.equalTo('objectId', request.params.template_id);
|
||||
template.equalTo('CreatedBy', userPtr);
|
||||
template.include('ExtUserPtr.TenantId');
|
||||
const res = await template.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const isArchive = res.get('IsArchive');
|
||||
if (isArchive && isArchive) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_template',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Template not found!' });
|
||||
} else {
|
||||
const template = Parse.Object.extend('contracts_Template');
|
||||
const deleteQuery = new template();
|
||||
deleteQuery.id = request.params.template_id;
|
||||
deleteQuery.set('IsArchive', true);
|
||||
const deleteRes = await deleteQuery.save(null, { useMasterKey: true });
|
||||
if (deleteRes) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_template',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: request.params.template_id,
|
||||
deletedAt: deleteRes.get('updatedAt'),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_template',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Template not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
export default async function deleteWebhook(request, response) {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const query = new Parse.Query('contracts_Users');
|
||||
query.equalTo('UserId', userPtr);
|
||||
const user = await query.first({ useMasterKey: true });
|
||||
if (user) {
|
||||
const updateQuery = new Parse.Object('contracts_Users');
|
||||
updateQuery.id = user.id;
|
||||
updateQuery.unset('Webhook');
|
||||
const res = await updateQuery.save(null, { useMasterKey: true });
|
||||
if (res) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_webhook',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
result: 'Webhook deleted successfully!',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_delete_webhook',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'User not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
export default async function getContact(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const Contactbook = new Parse.Query('contracts_Contactbook');
|
||||
Contactbook.equalTo('objectId', request.params.contact_id);
|
||||
Contactbook.equalTo('CreatedBy', userPtr);
|
||||
Contactbook.notEqualTo('IsDeleted', true);
|
||||
Contactbook.select('Name,Email,Phone');
|
||||
|
||||
const res = await Contactbook.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const parseRes = JSON.parse(JSON.stringify(res));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_contact',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: parseRes.objectId,
|
||||
name: parseRes.Name,
|
||||
email: parseRes.Email,
|
||||
phone: parseRes?.Phone || '',
|
||||
createdAt: parseRes.createdAt,
|
||||
updatedAt: parseRes.updatedAt,
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_contact',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Contact not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
export default async function getContactList(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const limit = request?.query?.limit ? parseInt(request.query.limit) : 100;
|
||||
const skip = request?.query?.skip ? parseInt(request.query.skip) : 0;
|
||||
const Contactbook = new Parse.Query('contracts_Contactbook');
|
||||
Contactbook.equalTo('CreatedBy', userPtr);
|
||||
Contactbook.notEqualTo('IsDeleted', true);
|
||||
Contactbook.limit(limit);
|
||||
Contactbook.skip(skip);
|
||||
Contactbook.descending('createdAt');
|
||||
const res = await Contactbook.find({ useMasterKey: true });
|
||||
if (res && res.length > 0) {
|
||||
const parseRes = JSON.parse(JSON.stringify(res));
|
||||
const contactlist = parseRes.map(x => ({
|
||||
objectId: x.objectId,
|
||||
name: x.Name,
|
||||
email: x.Email,
|
||||
phone: x?.Phone || '',
|
||||
createdAt: x.createdAt,
|
||||
updatedAt: x.updatedAt,
|
||||
}));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_contact_list',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({ result: contactlist });
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_contact_list',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({ result: [] });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
export default async function getDocument(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const Document = new Parse.Query('contracts_Document');
|
||||
Document.equalTo('objectId', request.params.document_id);
|
||||
Document.equalTo('CreatedBy', userPtr);
|
||||
Document.notEqualTo('IsArchive', true);
|
||||
Document.include('Signers');
|
||||
Document.include('Folder');
|
||||
Document.include('ExtUserPtr');
|
||||
Document.include('Placeholders.signerPtr');
|
||||
Document.include('ExtUserPtr.TenantId');
|
||||
const res = await Document.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const document = JSON.parse(JSON.stringify(res));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_document',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: document.objectId,
|
||||
title: document.Name,
|
||||
note: document.Note || '',
|
||||
folder: { objectId: document?.Folder?.objectId, name: document?.Folder?.Name } || '',
|
||||
file: document?.SignedUrl || document.URL,
|
||||
certificate: document?.CertificateUrl || '',
|
||||
owner: document?.ExtUserPtr?.Name,
|
||||
signers:
|
||||
document?.Placeholders?.map(y => ({
|
||||
role: y.Role,
|
||||
name: y?.signerPtr?.Name || '',
|
||||
email: y?.signerPtr?.Email || '',
|
||||
phone: y?.signerPtr?.Phone || '',
|
||||
widgets: y.placeHolder?.flatMap(x =>
|
||||
x?.pos.map(w => ({
|
||||
type: w?.type ? w.type : w.isStamp ? 'stamp' : 'signature',
|
||||
x: w.xPosition,
|
||||
y: w.yPosition,
|
||||
w: w?.Width || 150,
|
||||
h: w?.Height || 60,
|
||||
page: x?.pageNumber,
|
||||
}))
|
||||
),
|
||||
})) ||
|
||||
document?.Signers?.map(y => ({ name: y?.Name, email: y?.Email, phone: y?.Phone })) ||
|
||||
[],
|
||||
sendInOrder: document?.SendinOrder || false,
|
||||
enableOTP: document?.IsEnableOTP || false,
|
||||
createdAt: document.createdAt,
|
||||
updatedAt: document.updatedAt,
|
||||
enableTour: document?.IsTourEnabled || false,
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_document',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Document not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import reportJson from '../../../parsefunction/reportsJson.js';
|
||||
import dotenv from 'dotenv';
|
||||
import { cloudServerUrl } from '../../../../Utils.js';
|
||||
dotenv.config();
|
||||
|
||||
export default async function getDocumentList(request, response) {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
const appId = process.env.APP_ID;
|
||||
const serverUrl = cloudServerUrl; //process.env.SERVER_URL;
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const docType = request.params.doctype;
|
||||
const limit = request?.query?.limit ? request.query.limit : 100;
|
||||
const skip = request?.query?.skip ? request.query.skip : 0;
|
||||
let reportId;
|
||||
switch (docType) {
|
||||
case 'draft':
|
||||
reportId = 'ByHuevtCFY';
|
||||
break;
|
||||
case 'signaturerequest':
|
||||
reportId = '4Hhwbp482K';
|
||||
break;
|
||||
case 'inprogress':
|
||||
reportId = '1MwEuxLEkF';
|
||||
break;
|
||||
case 'completed':
|
||||
reportId = 'kQUoW4hUXz';
|
||||
break;
|
||||
case 'expired':
|
||||
reportId = 'zNqBHXHsYH';
|
||||
break;
|
||||
case 'declined':
|
||||
reportId = 'UPr2Fm5WY3';
|
||||
break;
|
||||
default:
|
||||
reportId = '';
|
||||
}
|
||||
const json = reportId && reportJson(reportId, userPtr.objectId);
|
||||
const clsName = 'contracts_Document';
|
||||
if (reportId && json) {
|
||||
const { params, keys } = json;
|
||||
const orderBy = '-updatedAt';
|
||||
const strParams = JSON.stringify(params);
|
||||
const strKeys = keys.join();
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': appId,
|
||||
'X-Parse-Master-Key': process.env.MASTER_KEY,
|
||||
};
|
||||
const url = `${serverUrl}/classes/${clsName}?where=${strParams}&keys=${strKeys},Placeholders&order=${orderBy}&skip=${skip}&limit=${limit}&include=AuditTrail.UserPtr,Placeholders.signerPtr,ExtUserPtr.TenantId`;
|
||||
try {
|
||||
const res = await axios.get(url, { headers: headers });
|
||||
if (res.data && res.data.results.length > 0) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: `api_get_document_list_${docType}`,
|
||||
properties: { response_code: 200, doc_type: docType },
|
||||
});
|
||||
}
|
||||
const updateRes = res.data.results.map(x => ({
|
||||
objectId: x.objectId,
|
||||
title: x.Name,
|
||||
note: x.Note || '',
|
||||
folder: { objectId: x?.Folder?.objectId, name: x?.Folder?.Name } || '',
|
||||
// file: x?.SignedUrl || x.URL,
|
||||
owner: x?.ExtUserPtr?.Name,
|
||||
signers:
|
||||
x?.Placeholders?.map(y => ({
|
||||
role: y.Role,
|
||||
name: y?.signerPtr?.Name || '',
|
||||
email: y?.signerPtr?.Email || '',
|
||||
phone: y?.signerPtr?.Phone || '',
|
||||
widgets: y.placeHolder?.flatMap(x =>
|
||||
x?.pos.map(w => ({
|
||||
type: w?.type ? w.type : w.isStamp ? 'stamp' : 'signature',
|
||||
x: w.xPosition,
|
||||
y: w.yPosition,
|
||||
w: w?.Width || 150,
|
||||
h: w?.Height || 60,
|
||||
page: x?.pageNumber,
|
||||
}))
|
||||
),
|
||||
})) ||
|
||||
x?.Signers?.map(y => ({ name: y?.Name, email: y?.Email, phone: y?.Phone })) ||
|
||||
[],
|
||||
sendInOrder: x?.SendinOrder || false,
|
||||
enableOTP: x?.IsEnableOTP || false,
|
||||
createdAt: x.createdAt,
|
||||
updatedAt: x.updatedAt,
|
||||
enableTour: x?.IsTourEnabled || false,
|
||||
}));
|
||||
return response.json({ result: updateRes });
|
||||
} else {
|
||||
return response.json({ result: [] });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err in getdocument list', err);
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: `api_get_document_list_${docType}`,
|
||||
properties: { response_code: 400, doc_type: docType },
|
||||
});
|
||||
}
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: `api_get_document_list_${docType}`,
|
||||
properties: { response_code: 404, doc_type: docType },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Report not available!' });
|
||||
}
|
||||
}
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
} catch (err) {
|
||||
console.log('Err', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
export default async function getFolder(request, response) {
|
||||
const apiToken = request.headers['x-api-token'];
|
||||
const folder_id = request.params.folder_id;
|
||||
if (!apiToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', apiToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const folderCls = new Parse.Query('contracts_Document');
|
||||
folderCls.equalTo('CreatedBy', userPtr);
|
||||
folderCls.equalTo('objectId', folder_id);
|
||||
folderCls.equalTo('Type', 'Folder');
|
||||
folderCls.notEqualTo('IsArchive', true);
|
||||
folderCls.descending('createdAt');
|
||||
folderCls.include('Folder');
|
||||
folderCls.include('ExtUserPtr.TenantId');
|
||||
const res = await folderCls.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const parseRes = JSON.parse(JSON.stringify(res));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_folder',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: parseRes.objectId,
|
||||
folderName: parseRes.Name,
|
||||
parentFolderId: parseRes?.Folder?.objectId || '',
|
||||
parentFolderName: parseRes?.Folder?.Name || '',
|
||||
createdAt: parseRes.createdAt,
|
||||
updatedAt: parseRes.updatedAt,
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_folder',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'folder not found.' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
export default async function getFolderList(request, response) {
|
||||
const apiToken = request.headers['x-api-token'];
|
||||
const parentFolderId = request.query?.parentFolderId || '';
|
||||
if (!apiToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', apiToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const limit = request?.query?.limit ? parseInt(request.query.limit) : 100;
|
||||
const skip = request?.query?.skip ? parseInt(request.query.skip) : 0;
|
||||
const folderCls = new Parse.Query('contracts_Document');
|
||||
folderCls.equalTo('CreatedBy', userPtr);
|
||||
folderCls.equalTo('Type', 'Folder');
|
||||
folderCls.notEqualTo('IsArchive', true);
|
||||
folderCls.descending('createdAt');
|
||||
folderCls.include('Folder');
|
||||
if (parentFolderId) {
|
||||
folderCls.equalTo('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Document',
|
||||
objectId: parentFolderId,
|
||||
});
|
||||
} else {
|
||||
folderCls.doesNotExist('Folder');
|
||||
}
|
||||
folderCls.descending('createdAt');
|
||||
folderCls.include('ExtUserPtr.TenantId');
|
||||
folderCls.limit(limit);
|
||||
folderCls.skip(skip);
|
||||
const res = await folderCls.find({ useMasterKey: true });
|
||||
if (res && res.length > 0) {
|
||||
const parseRes = JSON.parse(JSON.stringify(res));
|
||||
const folderlist = parseRes.map(x => ({
|
||||
objectId: x.objectId,
|
||||
folderName: x.Name,
|
||||
parentFolderId: x?.Folder?.objectId || '',
|
||||
parentFolderName: x?.Folder?.Name || '',
|
||||
createdAt: x.createdAt,
|
||||
updatedAt: x.updatedAt,
|
||||
}));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_Folder_list',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({ result: folderlist });
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_Folder_list',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({ result: [] });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
export default async function getTemplate(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const Template = new Parse.Query('contracts_Template');
|
||||
Template.equalTo('objectId', request.params.template_id);
|
||||
Template.equalTo('CreatedBy', userPtr);
|
||||
Template.notEqualTo('IsArchive', true);
|
||||
Template.include('Signers');
|
||||
Template.include('Folder');
|
||||
Template.include('ExtUserPtr');
|
||||
Template.include('Placeholders.signerPtr');
|
||||
Template.include('ExtUserPtr.TenantId');
|
||||
const res = await Template.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const template = JSON.parse(JSON.stringify(res));
|
||||
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_template',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: template.objectId,
|
||||
title: template.Name,
|
||||
note: template.Note || '',
|
||||
folder: { objectId: template?.Folder?.objectId, name: template?.Folder?.Name } || '',
|
||||
file: template?.SignedUrl || template?.URL,
|
||||
owner: template?.ExtUserPtr?.Name,
|
||||
signers:
|
||||
template?.Placeholders?.map(y => ({
|
||||
role: y.Role,
|
||||
name: y?.signerPtr?.Name || '',
|
||||
email: y?.signerPtr?.Email || '',
|
||||
phone: y?.signerPtr?.Phone || '',
|
||||
widgets: y.placeHolder?.flatMap(x =>
|
||||
x?.pos.map(w => ({
|
||||
type: w?.type ? w.type : w.isStamp ? 'stamp' : 'signature',
|
||||
x: w.xPosition,
|
||||
y: w.yPosition,
|
||||
w: w?.Width || 150,
|
||||
h: w?.Height || 60,
|
||||
page: x?.pageNumber,
|
||||
}))
|
||||
),
|
||||
})) || [],
|
||||
sendInOrder: template?.SendinOrder || false,
|
||||
enableOTP: template?.IsEnableOTP || false,
|
||||
createdAt: template.createdAt,
|
||||
updatedAt: template.updatedAt,
|
||||
enableTour: template?.IsTourEnabled || false,
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_template',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Template not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import dotenv from 'dotenv';
|
||||
import { cloudServerUrl } from '../../../../Utils.js';
|
||||
dotenv.config();
|
||||
export default async function getTemplatetList(request, response) {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
const appId = process.env.APP_ID;
|
||||
const serverUrl = cloudServerUrl; //process.env.SERVER_URL;
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const limit = request?.query?.limit ? request.query.limit : 100;
|
||||
const skip = request?.query?.skip ? request.query.skip : 0;
|
||||
|
||||
const clsName = 'contracts_Template';
|
||||
const params = {
|
||||
Type: { $ne: 'Folder' },
|
||||
CreatedBy: userPtr,
|
||||
IsArchive: { $ne: true },
|
||||
};
|
||||
const keys = [
|
||||
'Name',
|
||||
'Note',
|
||||
'Description',
|
||||
'Folder.Name',
|
||||
'URL',
|
||||
'SignedUrl',
|
||||
'ExtUserPtr.Name',
|
||||
'Signers.Name',
|
||||
'Signers.Email',
|
||||
'Signers.Phone',
|
||||
'Placeholders',
|
||||
];
|
||||
const orderBy = '-updatedAt';
|
||||
const strParams = JSON.stringify(params);
|
||||
const strKeys = keys.join();
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': appId,
|
||||
'X-Parse-Master-Key': process.env.MASTER_KEY,
|
||||
};
|
||||
const url = `${serverUrl}/classes/${clsName}?where=${strParams}&keys=${strKeys}&order=${orderBy}&skip=${skip}&limit=${limit}&include=AuditTrail.UserPtr,Placeholders.signerPtr,ExtUserPtr.TenantId`;
|
||||
const res = await axios.get(url, { headers: headers });
|
||||
if (res.data && res.data.results.length > 0) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_template_list',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
const updateRes = res.data.results.map(template => ({
|
||||
objectId: template.objectId,
|
||||
title: template.Name,
|
||||
note: template.Note || '',
|
||||
folder: { objectId: template?.Folder?.objectId, name: template?.Folder?.Name } || '',
|
||||
file: template?.SignedUrl || template.URL,
|
||||
owner: template?.ExtUserPtr?.Name,
|
||||
signers:
|
||||
template?.Placeholders?.map(y => ({
|
||||
role: y.Role,
|
||||
name: y?.signerPtr?.Name || '',
|
||||
email: y?.signerPtr?.Email || '',
|
||||
phone: y?.signerPtr?.Phone || '',
|
||||
widgets: y.placeHolder?.flatMap(x =>
|
||||
x?.pos.map(w => ({
|
||||
type: w?.type ? w.type : w.isStamp ? 'stamp' : 'signature',
|
||||
x: w.xPosition,
|
||||
y: w.yPosition,
|
||||
w: w?.Width || 150,
|
||||
h: w?.Height || 60,
|
||||
page: x?.pageNumber,
|
||||
}))
|
||||
),
|
||||
})) || [],
|
||||
sendInOrder: template?.SendinOrder || false,
|
||||
enableOTP: template?.IsEnableOTP || false,
|
||||
createdAt: template.createdAt,
|
||||
updatedAt: template.updatedAt,
|
||||
enableTour: template?.IsTourEnabled || false,
|
||||
}));
|
||||
|
||||
return response.json({ result: updateRes });
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_template_list',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({ result: [] });
|
||||
}
|
||||
}
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
} catch (err) {
|
||||
console.log('err', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
|
||||
export default async function getUser(request, response) {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const query = new Parse.Query('contracts_Users');
|
||||
query.equalTo('UserId', userPtr);
|
||||
query.exclude('IsContactEntry,TourStatus,UserRole,TenantId,UserId,CreatedBy,Plan');
|
||||
const user = await query.first({ useMasterKey: true });
|
||||
if (user) {
|
||||
const parseRes = JSON.parse(JSON.stringify(user));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_your_account_details',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: parseRes.objectId,
|
||||
name: parseRes.Name,
|
||||
email: parseRes.Email,
|
||||
phone: parseRes?.Phone || '',
|
||||
jobTitle: parseRes.JobTitle,
|
||||
company: parseRes.Company,
|
||||
createdAt: parseRes.createdAt,
|
||||
updatedAt: parseRes.updatedAt,
|
||||
});
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_your_account_details',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'User not found!' });
|
||||
}
|
||||
}
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
} catch (err) {
|
||||
console.log('Err', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
export default async function getWebhook(request, response) {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const query = new Parse.Query('contracts_Users');
|
||||
query.equalTo('UserId', userPtr);
|
||||
const user = await query.first({ useMasterKey: true });
|
||||
if (user) {
|
||||
const extUser = JSON.parse(JSON.stringify(user));
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_webhook',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
if (extUser && extUser.Webhook) {
|
||||
return response.json({
|
||||
webhook: extUser.Webhook,
|
||||
});
|
||||
} else {
|
||||
return response.json({});
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_get_webhook',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'User not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { cloudServerUrl, replaceMailVaribles } from '../../../../Utils.js';
|
||||
|
||||
export default async function resendMail(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
const docId = request.body.document_id;
|
||||
const userMail = request.body.email;
|
||||
const email_subject = request.body.email_subject;
|
||||
const email_body = request.body.email_body;
|
||||
const baseUrl = new URL(process.env.SERVER_URL);
|
||||
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const docQuery = new Parse.Query('contracts_Document');
|
||||
docQuery.equalTo('objectId', docId);
|
||||
docQuery.equalTo('CreatedBy', userPtr);
|
||||
docQuery.include('Signers,ExtUserPtr');
|
||||
docQuery.notEqualTo('IsCompleted', true);
|
||||
docQuery.notEqualTo('IsDeclined', true);
|
||||
docQuery.notEqualTo('IsArchive', true);
|
||||
docQuery.greaterThanOrEqualTo('ExpiryDate', new Date());
|
||||
docQuery.exists('SignedUrl');
|
||||
docQuery.include('ExtUserPtr.TenantId');
|
||||
const resDoc = await docQuery.first({ useMasterKey: true });
|
||||
// console.log("resDoc ",resDoc)
|
||||
if (resDoc) {
|
||||
const _resDoc = resDoc.toJSON();
|
||||
const contact = _resDoc.Signers.find(x => x.Email === userMail);
|
||||
const activeMailAdapter = _resDoc?.ExtUserPtr?.active_mail_adapter || '';
|
||||
if (contact) {
|
||||
try {
|
||||
const imgPng = 'https://qikinnovation.ams3.digitaloceanspaces.com/logo.png';
|
||||
let url = `${cloudServerUrl}/functions/sendmailv3/`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': process.env.APP_ID,
|
||||
'X-Parse-Master-Key': process.env.MASTER_KEY,
|
||||
};
|
||||
|
||||
const objectId = contact.objectId;
|
||||
const hostUrl = baseUrl.origin;
|
||||
const title = _resDoc.Name;
|
||||
const receiverMail = contact.Email;
|
||||
//encode this url value `${response.id}/${receiverMail}/${objectId}` to base64 using `btoa` function
|
||||
const encodeBase64 = btoa(`${_resDoc.objectId}/${receiverMail}/${objectId}`);
|
||||
let signPdf = `${hostUrl}/login/${encodeBase64}`;
|
||||
const openSignUrl = 'https://www.opensignlabs.com/contact-us';
|
||||
const orgName = _resDoc.ExtUserPtr.Company ? _resDoc.ExtUserPtr.Company : '';
|
||||
const newDate = new Date(_resDoc.ExpiryDate.iso);
|
||||
newDate.setDate(newDate.getDate() + 15);
|
||||
const sender = _resDoc.ExtUserPtr.Email;
|
||||
const localExpireDate = newDate.toLocaleDateString('en-US', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
});
|
||||
|
||||
const themeBGcolor = '#47a3ad';
|
||||
const email_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: white;padding-bottom: 20px;'> <div style='padding:10px 10px 0 10px'><img src=" +
|
||||
imgPng +
|
||||
" height='50' style='padding:20px; width:170px; height:40px;' /></div> <div style='padding:2px; font-family: system-ui;background-color:" +
|
||||
themeBGcolor +
|
||||
";'><p style='font-size: 20px;font-weight: 400;color: white;padding-left: 20px;' > Digital Signature Request</p></div><div><p style='padding: 20px;font-family: system-ui;font-size: 14px; margin-bottom: 10px;'> " +
|
||||
_resDoc.ExtUserPtr.Name +
|
||||
' has requested you to review and sign <strong> ' +
|
||||
title +
|
||||
"</strong>.</p><div style='padding: 5px 0px 5px 25px;display: flex;flex-direction: row;justify-content: space-around;'><table> <tr> <td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Sender</td> <td> </td> <td style='color:#626363;font-weight:bold'>" +
|
||||
sender +
|
||||
"</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Organization</td> <td> </td><td style='color:#626363;font-weight:bold'> " +
|
||||
orgName +
|
||||
"</td></tr> <tr> <td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Expires on</td><td> </td> <td style='color:#626363;font-weight:bold'>" +
|
||||
localExpireDate +
|
||||
"</td></tr><tr> <td></td> <td> </td></tr></table> </div> <div style='margin-left:70px'><a target=_blank href=" +
|
||||
signPdf +
|
||||
"> <button style='padding: 12px 12px 12px 12px;background-color: #d46b0f;color: white; border: 0px;box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px,rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;font-weight:bold;margin-top:30px'>Sign here</button></a> </div> <div style='display: flex; justify-content: center;margin-top: 10px;'> </div></div></div><div><p> This is an automated email from OpenSign™. For any queries regarding this email, please contact the sender " +
|
||||
sender +
|
||||
' directly.If you think this email is inappropriate or spam, you may file a complaint with OpenSign™ <a href=' +
|
||||
openSignUrl +
|
||||
' target=_blank>here</a>.</p> </div></div></body> </html>';
|
||||
let replaceVar;
|
||||
const variables = {
|
||||
document_title: title,
|
||||
sender_name: _resDoc.ExtUserPtr.Name,
|
||||
sender_mail: _resDoc.ExtUserPtr.Email,
|
||||
sender_phone: _resDoc.ExtUserPtr?.Phone || '',
|
||||
receiver_name: contact.Name,
|
||||
receiver_email: contact.Email,
|
||||
receiver_phone: contact?.Phone || '',
|
||||
expiry_date: localExpireDate,
|
||||
company_name: orgName,
|
||||
signing_url: signPdf,
|
||||
};
|
||||
if (email_subject && email_body) {
|
||||
replaceVar = replaceMailVaribles(email_subject, email_body, variables);
|
||||
} else if (email_subject) {
|
||||
replaceVar = replaceMailVaribles(email_subject, '', variables);
|
||||
replaceVar = { subject: replaceVar.subject, body: email_html };
|
||||
} else if (email_body) {
|
||||
replaceVar = replaceMailVaribles(
|
||||
`${_resDoc.ExtUserPtr.Name} has requested you to sign "${title}"`,
|
||||
email_body,
|
||||
variables
|
||||
);
|
||||
} else {
|
||||
replaceVar = {
|
||||
subject: `${_resDoc.ExtUserPtr.Name} has requested you to sign "${title}"`,
|
||||
body: email_html,
|
||||
};
|
||||
}
|
||||
const subject = replaceVar.subject;
|
||||
const html = replaceVar.body;
|
||||
|
||||
let params = {
|
||||
recipient: contact.Email,
|
||||
subject: subject,
|
||||
from: sender,
|
||||
html: html,
|
||||
extUserId: _resDoc.ExtUserPtr.objectId,
|
||||
mailProvider: activeMailAdapter,
|
||||
};
|
||||
|
||||
const res = await axios.post(url, params, { headers: headers });
|
||||
if (res.data.result && res.data.result.status === 'success') {
|
||||
return response.json({ result: 'mail sent successfully.' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('error', error);
|
||||
return response.status(400).json({ error: error.message });
|
||||
}
|
||||
} else {
|
||||
return response.status(404).json({ error: 'user not found.' });
|
||||
}
|
||||
} else {
|
||||
return response.status(404).json({ error: 'document not found.' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token.' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err in resendmail', err);
|
||||
return response.status(400).json({ error: err.message || 'Something went wrong.' });
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
export default async function saveWebhook(request, response) {
|
||||
const Url = request.body.url;
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
const query = new Parse.Query('contracts_Users');
|
||||
query.equalTo('UserId', userPtr);
|
||||
const user = await query.first({ useMasterKey: true });
|
||||
if (user) {
|
||||
const extUser = JSON.parse(JSON.stringify(user));
|
||||
const isUrlExist = extUser?.Webhook && extUser?.Webhook === Url;
|
||||
|
||||
if (!isUrlExist) {
|
||||
try {
|
||||
const updateQuery = new Parse.Object('contracts_Users');
|
||||
updateQuery.id = user.id;
|
||||
updateQuery.set('Webhook', Url);
|
||||
const res = await updateQuery.save(null, { useMasterKey: true });
|
||||
if (res) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_save_webhook',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
result: 'Webhook updated successfully!',
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_save_webhook',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
console.log('Err ', err);
|
||||
return response
|
||||
.status(400)
|
||||
.json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_save_webhook',
|
||||
properties: { response_code: 401 },
|
||||
});
|
||||
}
|
||||
return response.status(401).json({ error: 'Webhook url already exists!' });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_save_webhook',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'User not found!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
export default async function updateDocument(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const allowedKeys = ['name', 'note', 'description', 'folderId', 'enableOTP', 'enableTour'];
|
||||
const objectKeys = Object.keys(request.body);
|
||||
const isValid = objectKeys.every(key => allowedKeys.includes(key)) && objectKeys.length > 0;
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
if (isValid) {
|
||||
const document = new Parse.Query('contracts_Document');
|
||||
document.equalTo('objectId', request.params.document_id);
|
||||
document.equalTo('CreatedBy', userPtr);
|
||||
document.include('ExtUserPtr.TenantId');
|
||||
const res = await document.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const isArchive = res.get('IsArchive');
|
||||
if (isArchive && isArchive) {
|
||||
return response.status(404).json({ message: 'Document not found!' });
|
||||
} else {
|
||||
const document = Parse.Object.extend('contracts_Document');
|
||||
const updateQuery = new document();
|
||||
updateQuery.id = request.params.document_id;
|
||||
if (request?.body?.name) {
|
||||
updateQuery.set('Name', request?.body?.name);
|
||||
}
|
||||
if (request?.body?.note) {
|
||||
updateQuery.set('Note', request?.body?.note);
|
||||
}
|
||||
if (request?.body?.description) {
|
||||
updateQuery.set('Description', request?.body?.description);
|
||||
}
|
||||
if (request?.body?.folderId) {
|
||||
updateQuery.set('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Document',
|
||||
objectId: request?.body?.folderId,
|
||||
});
|
||||
}
|
||||
if (request.body?.enableOTP !== undefined) {
|
||||
updateQuery.set('IsEnableOTP', request.body?.enableOTP);
|
||||
}
|
||||
if (request.body?.enableTour !== undefined) {
|
||||
updateQuery.set('IsTourEnabled', request.body?.enableTour);
|
||||
}
|
||||
const updatedRes = await updateQuery.save(null, { useMasterKey: true });
|
||||
if (updatedRes) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_document',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: updatedRes.id,
|
||||
updatedAt: updatedRes.get('updatedAt'),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_document',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Document not found!' });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_document',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response.status(400).json({ error: 'Please provide valid field names!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
export default async function updateFolder(request, response) {
|
||||
const apiToken = request.headers['x-api-token'];
|
||||
const folderId = request.params.folder_id;
|
||||
const name = request.body.folderName;
|
||||
const parentFolderId = request.body.parentFolderId;
|
||||
if (!apiToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
try {
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', apiToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
|
||||
const folderCls = new Parse.Query('contracts_Document');
|
||||
folderCls.equalTo('CreatedBy', userPtr);
|
||||
folderCls.equalTo('objectId', folderId);
|
||||
folderCls.equalTo('Type', 'Folder');
|
||||
folderCls.notEqualTo('IsArchive', true);
|
||||
folderCls.include('ExtUserPtr.TenantId');
|
||||
const res = await folderCls.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const updateFolder = new Parse.Object('contracts_Document');
|
||||
updateFolder.id = res.id;
|
||||
updateFolder.set('Name', name);
|
||||
if (parentFolderId) {
|
||||
updateFolder.set('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Document',
|
||||
objectId: parentFolderId,
|
||||
});
|
||||
}
|
||||
const updateRes = await updateFolder.save(null, { useMasterKey: true });
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_folder',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({ objectId: updateRes.id, updatedAt: updateRes.updatedAt });
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_folder',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'folder not found.' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
export default async function updateTemplate(request, response) {
|
||||
try {
|
||||
const reqToken = request.headers['x-api-token'];
|
||||
if (!reqToken) {
|
||||
return response.status(400).json({ error: 'Please Provide API Token' });
|
||||
}
|
||||
const tokenQuery = new Parse.Query('appToken');
|
||||
tokenQuery.equalTo('token', reqToken);
|
||||
tokenQuery.include('userId');
|
||||
const token = await tokenQuery.first({ useMasterKey: true });
|
||||
if (token !== undefined) {
|
||||
// Valid Token then proceed request
|
||||
const allowedKeys = ['name', 'note', 'description', 'folderId', 'enableOTP', 'enableTour'];
|
||||
const objectKeys = Object.keys(request.body);
|
||||
const isValid = objectKeys.every(key => allowedKeys.includes(key)) && objectKeys.length > 0;
|
||||
const parseUser = JSON.parse(JSON.stringify(token));
|
||||
const userPtr = {
|
||||
__type: 'Pointer',
|
||||
className: '_User',
|
||||
objectId: parseUser.userId.objectId,
|
||||
};
|
||||
if (isValid) {
|
||||
const template = new Parse.Query('contracts_Template');
|
||||
template.equalTo('objectId', request.params.template_id);
|
||||
template.equalTo('CreatedBy', userPtr);
|
||||
template.include('ExtUserPtr.TenantId');
|
||||
const res = await template.first({ useMasterKey: true });
|
||||
if (res) {
|
||||
const isArchive = res.get('IsArchive');
|
||||
if (isArchive && isArchive) {
|
||||
return response.status(404).json({ message: 'Template not found!' });
|
||||
} else {
|
||||
const template = Parse.Object.extend('contracts_Template');
|
||||
const updateQuery = new template();
|
||||
updateQuery.id = request.params.template_id;
|
||||
if (request?.body?.name) {
|
||||
updateQuery.set('Name', request?.body?.name);
|
||||
}
|
||||
if (request?.body?.note) {
|
||||
updateQuery.set('Note', request?.body?.note);
|
||||
}
|
||||
if (request?.body?.description) {
|
||||
updateQuery.set('Description', request?.body?.description);
|
||||
}
|
||||
if (request?.body?.folderId) {
|
||||
updateQuery.set('Folder', {
|
||||
__type: 'Pointer',
|
||||
className: 'contracts_Template',
|
||||
objectId: request?.body?.folderId,
|
||||
});
|
||||
}
|
||||
if (request.body?.enableOTP !== undefined) {
|
||||
updateQuery.set('IsEnableOTP', request.body?.enableOTP);
|
||||
}
|
||||
if (request.body?.enableTour !== undefined) {
|
||||
updateQuery.set('IsTourEnabled', request.body?.enableTour);
|
||||
}
|
||||
const updatedRes = await updateQuery.save(null, { useMasterKey: true });
|
||||
if (updatedRes) {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_template',
|
||||
properties: { response_code: 200 },
|
||||
});
|
||||
}
|
||||
return response.json({
|
||||
objectId: updatedRes.id,
|
||||
updatedAt: updatedRes.get('updatedAt'),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_template',
|
||||
properties: { response_code: 404 },
|
||||
});
|
||||
}
|
||||
return response.status(404).json({ error: 'Template not found!' });
|
||||
}
|
||||
} else {
|
||||
if (request.posthog) {
|
||||
request.posthog?.capture({
|
||||
distinctId: parseUser.userId.email,
|
||||
event: 'api_update_template',
|
||||
properties: { response_code: 400 },
|
||||
});
|
||||
}
|
||||
return response.status(400).json({ error: 'Please provide valid field names!' });
|
||||
}
|
||||
} else {
|
||||
return response.status(405).json({ error: 'Invalid API Token!' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
return response.status(400).json({ error: 'Something went wrong, please try again later!' });
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { createTransport } from 'nodemailer';
|
||||
import { appName } from '../../Utils.js';
|
||||
// Online Javascript Editor for free
|
||||
// Write, Edit and Run your Javascript code using JS Online Compiler
|
||||
|
||||
function generateOtpWithSum10() {
|
||||
let otp = [];
|
||||
let sum = 0;
|
||||
|
||||
// First, generate 3 random digits (0-9) and add them to the sum
|
||||
for (let i = 0; i < 3; i++) {
|
||||
let digit = Math.floor(Math.random() * 10);
|
||||
otp.push(digit);
|
||||
sum += digit;
|
||||
}
|
||||
|
||||
// Calculate the last digit to ensure the sum equals 10
|
||||
let lastDigit = 10 - sum;
|
||||
|
||||
// If the last digit is not valid (e.g., greater than 9), regenerate
|
||||
if (lastDigit >= 0 && lastDigit <= 9) {
|
||||
otp.push(lastDigit);
|
||||
} else {
|
||||
return generateOtpWithSum10(); // Recursively generate again
|
||||
}
|
||||
|
||||
return otp.join('');
|
||||
}
|
||||
|
||||
export default async function validateSmtp(request, response) {
|
||||
const host = request.body.host;
|
||||
const port = request.body?.port?.toString();
|
||||
const username = request.body.username;
|
||||
const password = request.body.password;
|
||||
const secure = request.body?.secure;
|
||||
const email = request.body?.email;
|
||||
const otp = generateOtpWithSum10();
|
||||
// console.log('Generated OTP:', otp);
|
||||
|
||||
try {
|
||||
const smtpsecure = secure || port !== '465' ? false : true;
|
||||
const transporterSMTP = createTransport({
|
||||
host: host,
|
||||
port: port,
|
||||
secure: smtpsecure,
|
||||
auth: { user: username, pass: password },
|
||||
});
|
||||
const from = appName;
|
||||
const mailsender = username;
|
||||
const messageParams = {
|
||||
from: from + ' <' + mailsender + '>',
|
||||
to: email,
|
||||
subject: `Your ${appName} SMTP credentials verification code`,
|
||||
text: 'mail',
|
||||
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 style='background-color:red;padding:2px;font-family:system-ui; background-color:#47a3ad;'> <p style='font-size:20px;font-weight:400;color:white;padding-left:20px',>SMTP Verification Code</p></div><div style='padding:20px'><p style='font-family:system-ui;font-size:14px'>Your verification code is:</p><p style=' text-decoration: none; font-weight: bolder; color:blue;font-size:45px;margin:20px'>` +
|
||||
otp +
|
||||
'</p></div> </div> </div></body></html>',
|
||||
};
|
||||
|
||||
const res = await transporterSMTP.sendMail(messageParams);
|
||||
console.log('custom smtp transporter res: ', res?.response);
|
||||
if (!res.err) {
|
||||
response.status(200).json({ message: 'success' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('err ', err);
|
||||
const code = err?.responseCode || 400;
|
||||
const message = err?.response || 'failed!';
|
||||
response.status(code).json({ error: message });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user