Merge pull request #754 from OpenSignLabs/feat_resendmail

feat: now user can send automatic reminders
This commit is contained in:
Amol
2024-05-20 15:44:54 +05:30
committed by GitHub
11 changed files with 539 additions and 137 deletions
@@ -1,6 +1,9 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import "../../styles/AddUser.css";
import { getFileName } from "../../constant/Utils";
import { checkIsSubscribed, getFileName } from "../../constant/Utils";
import PremiumAlertHeader from "../../primitives/PremiumAlertHeader";
import Upgrade from "../../primitives/Upgrade";
import { isEnableSubscription } from "../../constant/const";
// import SelectFolder from "../../premitives/SelectFolder";
const EditTemplate = ({ template, onSuccess }) => {
@@ -9,9 +12,21 @@ const EditTemplate = ({ template, onSuccess }) => {
Name: template?.Name || "",
Note: template?.Note || "",
Description: template?.Description || "",
SendinOrder: template?.SendinOrder ? `${template?.SendinOrder}` : "false"
SendinOrder: template?.SendinOrder ? `${template?.SendinOrder}` : "false",
AutomaticReminders: template?.AutomaticReminders || false,
RemindOnceInEvery: template?.RemindOnceInEvery || 5
});
const [isSubscribe, setIsSubscribe] = useState(false);
useEffect(() => {
fetchSubscription();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const fetchSubscription = async () => {
if (isEnableSubscription) {
const getIsSubscribe = await checkIsSubscribed();
setIsSubscribe(getIsSubscribe);
}
};
const handleStrInput = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
@@ -25,12 +40,26 @@ const EditTemplate = ({ template, onSuccess }) => {
e.preventDefault();
e.stopPropagation();
const isChecked = formData.SendinOrder === "true" ? true : false;
const data = { ...formData, SendinOrder: isChecked };
const AutoReminder = formData?.AutomaticReminders || false;
let reminderDate = {};
if (AutoReminder) {
const RemindOnceInEvery = parseInt(formData?.RemindOnceInEvery);
const ReminderDate = new Date(template?.createdAt);
ReminderDate.setDate(ReminderDate.getDate() + RemindOnceInEvery);
reminderDate = { NextReminderDate: ReminderDate };
}
const data = { ...formData, SendinOrder: isChecked, ...reminderDate };
onSuccess(data);
};
const handleAutoReminder = () => {
setFormData((prev) => ({
...prev,
AutomaticReminders: !formData.AutomaticReminders
}));
};
return (
<div className="addusercontainer">
<div className="max-h-[300px] md:max-h-[400px] overflow-y-scroll p-[10px]">
<div className="form-wrapper">
<form onSubmit={handleSubmit}>
<div>
@@ -128,6 +157,57 @@ const EditTemplate = ({ template, onSuccess }) => {
<div style={{ fontSize: 12 }}>No</div>
</div>
</div>
<div className="text-xs mt-2">
{!isEnableSubscription && (
<PremiumAlertHeader
message={
"Disable Auto reminder is free in beta, this feature will incur a fee later."
}
/>
)}
<span
className={
isSubscribe || !isEnableSubscription
? "font-semibold"
: "font-semibold text-gray-300"
}
>
Auto reminder{" "}
{!isSubscribe && isEnableSubscription && <Upgrade />}
</span>
<label
className={`${
isSubscribe || !isEnableSubscription
? "cursor-pointer "
: "pointer-events-none opacity-50"
} relative block items-center mb-0`}
>
<input
checked={formData.AutomaticReminders}
onChange={handleAutoReminder}
type="checkbox"
value=""
className="sr-only peer"
/>
<div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-1 peer-focus:ring-black rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-black peer-checked:bg-blue-600 mt-2"></div>
</label>
</div>
{isSubscribe && formData?.AutomaticReminders === true && (
<div className="text-xs mt-2">
<label className="block">
Remind once in every (Days)
<span className="text-red-500 text-[13px]">*</span>
</label>
<input
type="number"
value={formData.RemindOnceInEvery}
name="RemindOnceInEvery"
className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs"
onChange={handleStrInput}
required
/>
</div>
)}
{/* <SelectFolder onSuccess={handleFolder} folderCls={"contracts_Template"} /> */}
<div className="buttoncontainer">
<button type="submit" className="submitbutton">
+6 -4
View File
@@ -561,7 +561,7 @@ export const signPdfFun = async (
isCustomCompletionMail = true;
}
}
// below for loop is used to get first signature of user to send if to signpdf
// for adding it in completion certificate
let getSignature;
@@ -676,7 +676,9 @@ export const createDocument = async (template, placeholders, signerData) => {
objectId: Doc.CreatedBy.objectId
},
Signers: signers,
SendinOrder: Doc?.SendinOrder || false
SendinOrder: Doc?.SendinOrder || false,
AutomaticReminders: Doc?.AutomaticReminders || false,
RemindOnceInEvery: parseInt(Doc?.RemindOnceInEvery || 5)
};
try {
@@ -1349,8 +1351,8 @@ export const multiSignEmbed = async (
position.type === radioButtonWidget
? 10
: position.type === "checkbox"
? 10
: newUpdateHeight;
? 10
: newUpdateHeight;
const newHeight = ind ? (ind > 0 ? widgetHeight : 0) : widgetHeight;
if (signyourself) {
+160 -84
View File
@@ -11,12 +11,14 @@ import SignersInput from "../components/shared/fields/SignersInput";
import Title from "../components/Title";
import PageNotFound from "./PageNotFound";
import { SaveFileSize } from "../constant/saveFileSize";
import { getFileName, toDataUrl } from "../constant/Utils";
import { checkIsSubscribed, getFileName, toDataUrl } from "../constant/Utils";
import { PDFDocument } from "pdf-lib";
import axios from "axios";
import { isEnableSubscription, submitBtn } from "../constant/const";
import ModalUi from "../primitives/ModalUi";
import { Tooltip } from "react-tooltip";
import Upgrade from "../primitives/Upgrade";
import PremiumAlertHeader from "../primitives/PremiumAlertHeader";
// `Form` render all type of Form on this basis of their provided in path
function Form() {
@@ -48,7 +50,9 @@ const Forms = (props) => {
TimeToCompleteDays: 15,
SendinOrder: "false",
password: "",
file: ""
file: "",
remindOnceInEvery: 5,
autoreminder: false
});
const [fileupload, setFileUpload] = useState("");
const [fileload, setfileload] = useState(false);
@@ -60,6 +64,7 @@ const Forms = (props) => {
const [isPassword, setIsPassword] = useState(false);
const [isDecrypting, setIsDecrypting] = useState(false);
const [isCorrectPass, setIsCorrectPass] = useState(true);
const [isSubscribe, setIsSubscribe] = useState(false);
const handleStrInput = (e) => {
setIsCorrectPass(true);
setFormData({ ...formData, [e.target.name]: e.target.value });
@@ -70,6 +75,17 @@ const Forms = (props) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.title]);
useEffect(() => {
fetchSubscription();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const fetchSubscription = async () => {
if (isEnableSubscription) {
const getIsSubscribe = await checkIsSubscribed();
setIsSubscribe(getIsSubscribe);
}
};
function getFileAsArrayBuffer(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -383,6 +399,8 @@ const Forms = (props) => {
if (props.title !== "Sign Yourself") {
const isChecked = formData.SendinOrder === "false" ? false : true;
object.set("SendinOrder", isChecked);
object.set("AutomaticReminders", formData.autoreminder);
object.set("RemindOnceInEvery", parseInt(formData.remindOnceInEvery));
}
object.set("URL", fileupload);
object.set("CreatedBy", Parse.User.createWithoutData(currentUser.id));
@@ -402,7 +420,6 @@ const Forms = (props) => {
className: "contracts_Users",
objectId: ExtCls[0].objectId
});
const res = await object.save();
if (res) {
setSigners([]);
@@ -457,7 +474,11 @@ const Forms = (props) => {
? "Note to myself"
: "Please review and sign this document",
TimeToCompleteDays: 15,
SendinOrder: "true"
SendinOrder: "true",
password: "",
file: "",
remindOnceInEvery: 5,
autoreminder: false
});
setFileUpload("");
setpercentage(0);
@@ -536,6 +557,9 @@ const Forms = (props) => {
inputFileRef.current.value = ""; // Set file input value to empty string
}
};
const handleAutoReminder = () => {
setFormData((prev) => ({ ...prev, autoreminder: !formData.autoreminder }));
};
return (
<div className="shadow-md rounded my-2 p-3 bg-[#ffffff] md:border-[1px] md:border-gray-600/50">
<Title title={props?.title} />
@@ -732,89 +756,141 @@ const Forms = (props) => {
</div>
)}
{props.title !== "Sign Yourself" && (
<div className="text-xs mt-2">
<label className="block">
Send In Order
<a data-tooltip-id="sendInOrder-tooltip" className="ml-1">
<sup>
<i
className="fa-solid fa-question rounded-full"
style={{
borderColor: "#33bbff",
color: "#33bbff",
fontSize: 13,
borderWidth: 1.5,
padding: "1.5px 4px"
}}
></i>
</sup>
</a>
<Tooltip id="sendInOrder-tooltip" className="z-50">
<div className="max-w-[200px] md:max-w-[450px]">
<p className="font-bold">Send in Order</p>
<p>
Choose how you want the signing requests to be sent to
the document signers:
</p>
<p className="p-[5px]">
<ol className="list-disc">
<li>
<span className="font-bold">Yes:</span>
<span>
{" "}
Selecting this option will send the signing
request to the first signer initially. Once the
first signer completes their part, the next signer
in the sequence will receive the request. This
process continues until all signers have signed
the document. This method ensures that the
document is signed in a specific order.
</span>
</li>
<li>
<span className="font-bold">No: </span>
<span>
Selecting this option will send the signing links
to all signers simultaneously. Every signer can
sign the document at their convenience, regardless
of whether other signers have completed their
signatures. This method is faster but does not
enforce any signing order among the participants.
</span>
</li>
</ol>
</p>
<>
<div className="text-xs mt-2">
<label className="block">
Send In Order
<a data-tooltip-id="sendInOrder-tooltip" className="ml-1">
<sup>
<i
className="fa-solid fa-question rounded-full"
style={{
borderColor: "#33bbff",
color: "#33bbff",
fontSize: 13,
borderWidth: 1.5,
padding: "1.5px 4px"
}}
></i>
</sup>
</a>
<Tooltip id="sendInOrder-tooltip" className="z-50">
<div className="max-w-[200px] md:max-w-[450px]">
<p className="font-bold">Send in Order</p>
<p>
Choose how you want the signing requests to be sent to
the document signers:
</p>
<p className="p-[5px]">
<ol className="list-disc">
<li>
<span className="font-bold">Yes:</span>
<span>
{" "}
Selecting this option will send the signing
request to the first signer initially. Once the
first signer completes their part, the next
signer in the sequence will receive the request.
This process continues until all signers have
signed the document. This method ensures that
the document is signed in a specific order.
</span>
</li>
<li>
<span className="font-bold">No: </span>
<span>
Selecting this option will send the signing
links to all signers simultaneously. Every
signer can sign the document at their
convenience, regardless of whether other signers
have completed their signatures. This method is
faster but does not enforce any signing order
among the participants.
</span>
</li>
</ol>
</p>
<p>
Select the option that best suits the needs of your
document processing.
</p>
</div>
</Tooltip>
</label>
<div className="flex items-center gap-2 ml-2 mb-1">
<input
type="radio"
value={"true"}
name="SendinOrder"
checked={formData.SendinOrder === "true"}
className=""
onChange={handleStrInput}
/>
<div className="text-center">Yes</div>
<p>
Select the option that best suits the needs of your
document processing.
</p>
</div>
</Tooltip>
</label>
<div className="flex items-center gap-2 ml-2 mb-1">
<input
type="radio"
value={"true"}
name="SendinOrder"
checked={formData.SendinOrder === "true"}
onChange={handleStrInput}
/>
<div className="text-center">Yes</div>
</div>
<div className="flex items-center gap-2 ml-2 mb-1">
<input
type="radio"
value={"false"}
name="SendinOrder"
checked={formData.SendinOrder === "false"}
onChange={handleStrInput}
/>
<div className="text-center">No</div>
</div>
</div>
<div className="flex items-center gap-2 ml-2 mb-1">
<input
type="radio"
value={"false"}
name="SendinOrder"
checked={formData.SendinOrder === "false"}
onChange={handleStrInput}
/>
<div className="text-center">No</div>
<div className="text-xs mt-2">
{!isEnableSubscription && (
<PremiumAlertHeader
message={
"Disable Auto reminder is free in beta, this feature will incur a fee later."
}
/>
)}
<span
className={
isSubscribe || !isEnableSubscription
? "font-semibold"
: "font-semibold text-gray-300"
}
>
Auto reminder{" "}
{!isSubscribe && isEnableSubscription && <Upgrade />}
</span>
<label
className={`${
isSubscribe || !isEnableSubscription
? "cursor-pointer "
: "pointer-events-none opacity-50"
} relative block items-center mb-0`}
>
<input
checked={formData.autoreminder}
onChange={handleAutoReminder}
type="checkbox"
value=""
className="sr-only peer"
/>
<div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-1 peer-focus:ring-black rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-black peer-checked:bg-blue-600 mt-2"></div>
</label>
</div>
</div>
{formData?.autoreminder === true && (
<div className="text-xs mt-2">
<label className="block">
Remind once in every (Days)
<span className="text-red-500 text-[13px]">*</span>
</label>
<input
type="number"
value={formData.remindOnceInEvery}
name="remindOnceInEvery"
className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs"
onChange={handleStrInput}
required
/>
</div>
)}
</>
)}
<div className="flex items-center mt-3 gap-2 text-white">
<button
+1 -1
View File
@@ -405,7 +405,7 @@ function PlaceHolderSign() {
};
setHandleError("Error: Something went wrong!");
setIsLoading(loadObj);
} else if (res[0] && res.length) {
} else if (res.length && res[0]?.objectId) {
setActiveMailAdapter(res[0]?.active_mail_adapter);
setSignerUserId(res[0].objectId);
const tourstatus = res[0].TourStatus && res[0].TourStatus;
+21 -27
View File
@@ -36,6 +36,7 @@ import AddRoleModal from "../components/pdf/AddRoleModal";
import PlaceholderCopy from "../components/pdf/PlaceholderCopy";
import TourContentWithBtn from "../primitives/TourContentWithBtn";
import DropdownWidgetOption from "../components/pdf/DropdownWidgetOption";
import Parse from "parse";
const TemplatePlaceholder = () => {
const navigate = useNavigate();
const { templateId } = useParams();
@@ -704,35 +705,29 @@ const TemplatePlaceholder = () => {
Name: pdfDetails[0]?.Name || "",
Note: pdfDetails[0]?.Note || "",
Description: pdfDetails[0]?.Description || "",
SendinOrder: pdfDetails[0]?.SendinOrder || false
SendinOrder: pdfDetails[0]?.SendinOrder || false,
AutomaticReminders: pdfDetails[0]?.AutomaticReminders,
RemindOnceInEvery: parseInt(pdfDetails[0]?.RemindOnceInEvery),
NextReminderDate: pdfDetails[0]?.NextReminderDate
};
const updateTemplate = new Parse.Object("contracts_Template");
updateTemplate.id = templateId;
for (const key in data) {
updateTemplate.set(key, data[key]);
}
await updateTemplate.save(null, {
sessionToken: localStorage.getItem("accesstoken")
});
await axios
.put(
`${localStorage.getItem("baseUrl")}classes/${localStorage.getItem(
"_appName"
)}_Template/${templateId}`,
data,
{
headers: {
"Content-Type": "application/json",
"X-Parse-Application-Id": localStorage.getItem("parseAppId"),
"X-Parse-Session-Token": localStorage.getItem("accesstoken")
}
}
)
.then(() => {
setIsCreateDocModal(true);
setIsMailSend(true);
const loadObj = {
isLoad: false
};
setIsLoading(loadObj);
})
.catch((err) => {
console.log("axois err ", err);
});
setIsCreateDocModal(true);
setIsMailSend(true);
const loadObj = {
isLoad: false
};
setIsLoading(loadObj);
} catch (e) {
setIsLoading(false);
alert("Something went wrong, please try again later.");
console.log("error", e);
}
} else {
@@ -1207,7 +1202,6 @@ const TemplatePlaceholder = () => {
setIsCheckbox(false);
};
console.log("signerpos", signerPos);
return (
<div>
<Title title={"Template"} />
@@ -139,7 +139,10 @@ const ReportTable = (props) => {
className: "_User",
objectId: Doc.CreatedBy.objectId
},
Signers: signers
Signers: signers,
SendinOrder: Doc?.SendinOrder || false,
AutomaticReminders: Doc?.AutomaticReminders || false,
RemindOnceInEvery: Doc?.RemindOnceInEvery || 5
};
try {
const res = await axios.post(
@@ -0,0 +1,231 @@
import axios from 'axios';
// `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;
}
export default async function autoReminder(request, response) {
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}}&nbsp;has requested you to review and sign&nbsp;<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 = `${process.env.SERVER_URL}/functions/sendmailv3`;
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': process.env.APP_ID,
};
const limit = request.query.limit || 2000;
const skip = request.query.skip || 0;
const baseUrl = new URL(process.env.PUBLIC_URL);
// 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(limit);
docQuery.skip(skip);
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');
const docsArr = await docQuery.find({ useMasterKey: true });
if (docsArr && docsArr.length > 0) {
const _docsArr = JSON.parse(JSON.stringify(docsArr));
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(doc?.NextReminderDate?.iso);
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) {
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}>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') {
// 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 sendmail', 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) {
// 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 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}>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 {
const res = await axios.post(url, params, { headers: headers });
// console.log('res ', res.data.result);
} catch (err) {
console.log('err in sendmail', err);
}
}
}
} 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) {
for (const signer of signers) {
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}>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 {
const res = await axios.post(url, params, { headers: headers });
// console.log('res ', res.data.result);
} catch (err) {
console.log('err in sendmail', err);
}
}
}
}
// 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);
}
}
}
response.json({ status: 'success' });
} 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 });
}
}
@@ -7,6 +7,7 @@ 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';
export const app = express();
dotenv.config();
@@ -16,10 +17,8 @@ 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('/savesubscription', saveSubscription);
app.post('/saveinvoice', saveInvoice);
app.post('/savepayment', savePayments);
app.post('/googleauth', gooogleauth);
app.post('/autoreminder', autoReminder);
@@ -14,19 +14,29 @@ async function DocumentAftersave(request) {
const updateQuery = await documentQuery.get(request.object.id, { useMasterKey: true });
updateQuery.set('ExpiryDate', ExpiryDate);
updateQuery.set('OriginIp', ip);
const AutoReminder = request?.object?.get('AutomaticReminders') || false;
if (AutoReminder) {
const RemindOnceInEvery = request?.object?.get('RemindOnceInEvery') || 5;
const ReminderDate = new Date(createdAt);
ReminderDate.setDate(ReminderDate.getDate() + RemindOnceInEvery);
updateQuery.set('NextReminderDate', ReminderDate);
}
await updateQuery.save(null, { useMasterKey: true });
} else if (createdAt && Folder === 'AIDoc') {
const TimeToCompleteDays = request.object.get('TimeToCompleteDays');
const ExpiryDate = new Date(createdAt);
// console.log("ExpiryDate")
// console.log(ExpiryDate)
ExpiryDate.setDate(ExpiryDate.getDate() + TimeToCompleteDays);
// console.log("ExpiryDate date after update")
// console.log(ExpiryDate)
const documentQuery = new Parse.Query('contracts_Document');
const updateQuery = await documentQuery.get(request.object.id, { useMasterKey: true });
updateQuery.set('ExpiryDate', ExpiryDate);
updateQuery.set('OriginIp', ip);
const AutoReminder = request?.object?.get('AutomaticReminders') || false;
if (AutoReminder) {
const RemindOnceInEvery = request?.object?.get('RemindOnceInEvery') || 5;
const ReminderDate = new Date(createdAt);
ReminderDate.setDate(ReminderDate.getDate() + RemindOnceInEvery);
updateQuery.set('NextReminderDate', ReminderDate);
}
await updateQuery.save(null, { useMasterKey: true });
}
@@ -26,7 +26,7 @@ export default async function GetTemplate(request) {
if (res) {
// console.log("res ",res)
const acl = res.getACL();
console.log("acl", acl.getReadAccess(userId))
// console.log("acl", acl.getReadAccess(userId))
if (acl && acl.getReadAccess(userId)) {
return res;
} else {
@@ -4,7 +4,14 @@ export default async function TemplateAfterSave(request) {
console.log('new entry is insert in contracts_Template');
// update acl of New Document If There are signers present in array
const signers = request.object.get('Signers');
const AutoReminder = request?.object?.get('AutomaticReminders') || false;
if (AutoReminder) {
const RemindOnceInEvery = request?.object?.get('RemindOnceInEvery') || 5;
const ReminderDate = new Date(request?.object?.get('createdAt'));
ReminderDate.setDate(ReminderDate.getDate() + RemindOnceInEvery);
request.object.set('NextReminderDate', ReminderDate);
await request.object.save(null, { useMasterKey: true });
}
if (signers && signers.length > 0) {
await updateAclDoc(request.object.id);
} else {