fix: quicksend validation

This commit is contained in:
prafull-opensignlabs
2024-08-21 12:57:08 +05:30
parent 5d89f724f4
commit 523d210503
7 changed files with 188 additions and 114 deletions
@@ -605,7 +605,7 @@
"user-name-exist": "user name already exist",
"format": "format",
"select-date-format": "Select a date format",
"buyapiaddon":"Buy APIs",
"buyapiaddon":"Buy APIs Credits",
"quantityofapis" :"Quantity of APIs",
"additionalapis":"Please purchase add-on APIs",
"remainingapis": "Remaining APIs Credits:",
@@ -605,7 +605,7 @@
"Add-seats": "Ajouter des sièges",
"format": "format",
"select-date-format": "Sélectionnez un format de date",
"buyapiaddon":"Acheter des API",
"buyapiaddon":"Acheter des API Crédits",
"quantityofapis":"Quantité d'API",
"additionalapis":"Veuillez acheter des API complémentaires",
"remainingapis":"API restantes Crédits:",
+34 -21
View File
@@ -5,6 +5,7 @@ import Loader from "../primitives/Loader";
import { useTranslation } from "react-i18next";
import Parse from "parse";
import ModalUi from "../primitives/ModalUi";
import { isEnableSubscription } from "../constant/const";
const BulkSendUi = (props) => {
const { t } = useTranslation();
const [forms, setForms] = useState([]);
@@ -32,24 +33,36 @@ const BulkSendUi = (props) => {
//function to check atleast one signature field exist
const signatureExist = async () => {
setIsSubmit(true);
try {
const allowedquicksend = await Parse.Cloud.run("allowedquicksend");
if (allowedquicksend > 0) {
setIsBulkAvailable(true);
const getPlaceholder = props.item?.Placeholders;
const checkIsSignatureExistt = getPlaceholder?.every((placeholderObj) =>
placeholderObj?.placeHolder?.some((holder) =>
holder?.pos?.some((posItem) => posItem?.type === "signature")
)
);
setIsSignatureExist(checkIsSignatureExistt);
if (isEnableSubscription) {
setIsSubmit(true);
try {
const allowedquicksend = await Parse.Cloud.run("allowedquicksend");
if (allowedquicksend > 0) {
setIsBulkAvailable(true);
const getPlaceholder = props.item?.Placeholders;
const checkIsSignatureExistt = getPlaceholder?.every(
(placeholderObj) =>
placeholderObj?.placeHolder?.some((holder) =>
holder?.pos?.some((posItem) => posItem?.type === "signature")
)
);
setIsSignatureExist(checkIsSignatureExistt);
}
setAmount((obj) => ({ ...obj, totalQuickSend: allowedquicksend }));
setIsSubmit(false);
} catch (err) {
setIsSubmit(false);
console.log("Err", err);
}
setAmount((obj) => ({ ...obj, totalQuickSend: allowedquicksend }));
setIsSubmit(false);
} catch (err) {
setIsSubmit(false);
console.log("Err", err);
} else {
setIsBulkAvailable(true);
const getPlaceholder = props.item?.Placeholders;
const checkIsSignatureExistt = getPlaceholder?.every((placeholderObj) =>
placeholderObj?.placeHolder?.some((holder) =>
holder?.pos?.some((posItem) => posItem?.type === "signature")
)
);
setIsSignatureExist(checkIsSignatureExistt);
}
};
useEffect(() => {
@@ -99,7 +112,9 @@ const BulkSendUi = (props) => {
const handleAddForm = (e) => {
e.preventDefault();
// Check if the quick send limit has been reached
if (forms.length <= amount.totalQuickSend) {
if (isEnableSubscription && forms.length >= amount.totalQuickSend) {
setIsQuotaReached(true);
} else {
if (forms?.length < allowedForm) {
if (props?.Placeholders.length > 0) {
let newForm = [];
@@ -124,8 +139,6 @@ const BulkSendUi = (props) => {
// If the limit has been reached, throw an error with the appropriate message
alert(t("quick-send-alert-4"));
}
} else {
setIsQuotaReached(true);
}
};
@@ -319,7 +332,7 @@ const BulkSendUi = (props) => {
</button>
<button
type="submit"
className="op-btn op-btn-secondary focus:outline-none"
className="op-btn op-btn-accent focus:outline-none"
>
<i className="fa-light fa-paper-plane"></i>{" "}
<span>{t("send")}</span>
+7 -7
View File
@@ -4,12 +4,12 @@ export const documentCls = "contracts_Document";
export const themeColor = "#47a3ad";
export const iconColor = "#686968";
export const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
export const isEnableSubscription =
process.env.REACT_APP_ENABLE_SUBSCRIPTION &&
process.env.REACT_APP_ENABLE_SUBSCRIPTION?.toLowerCase() === "true"
? true
: false;
export const isStaging =
window.location.origin === "https://staging-app.opensignlabs.com";
export const isEnableSubscription = false;
// process.env.REACT_APP_ENABLE_SUBSCRIPTION &&
// process.env.REACT_APP_ENABLE_SUBSCRIPTION?.toLowerCase() === "true"
// ? true
// : false;
export const isStaging = "http://localhost:3001";
// window.location.origin === "https://staging-app.opensignlabs.com";
export const isPublicStaging =
window.location.origin === "https://staging.opensign.me";
+2 -5
View File
@@ -249,10 +249,10 @@ function GenerateToken() {
</div>
</div>
</ModalUi>
{/* buy apis */}
{/* buy APIs */}
<ModalUi
isOpen={isModal.buyapis}
title={"Addon apis"}
title={"Buy Addon APIs"}
handleClose={handleBuyAPIsModal}
>
{isFormLoader && (
@@ -261,9 +261,6 @@ function GenerateToken() {
</div>
)}
<form onSubmit={handleAddOnApiSubmit} className="p-3">
<p className="flex justify-center text-center mx-2 mb-3 text-base op-text-accent font-medium">
{t("additionalapis")}
</p>
<div className="mb-3 flex justify-between">
<label
htmlFor="quantity"
@@ -782,13 +782,13 @@ const ReportTable = (props) => {
if (count > 1) {
setAlertMsg({
type: "success",
message: count + t("document-sent-alert")
message: count + " " + t("document-sent-alert")
});
setTimeout(() => setIsAlert(false), 1500);
} else {
setAlertMsg({
type: "success",
message: count + t("document-sent-alert")
message: count + " " + t("document-sent-alert")
});
setTimeout(() => setIsAlert(false), 1500);
}
@@ -3,7 +3,35 @@ import { cloudServerUrl } from '../../Utils.js';
const serverUrl = cloudServerUrl; //process.env.SERVER_URL;
const appId = process.env.APP_ID;
async function deductcount(tenantId, docs) {
try {
const subscription = new Parse.Query('contracts_Subscriptions');
subscription.equalTo('TenantId', {
__type: 'Pointer',
className: 'partners_Tenant',
objectId: tenantId,
});
subscription.include('ExtUserPtr');
subscription.greaterThan('AllowedQuicksend', 0);
const resSub = await subscription.first({ useMasterKey: true });
if (resSub) {
const updateApiCount =
resSub?.get('AllowedQuicksend') && resSub.get('AllowedQuicksend') > 0
? resSub.get('AllowedQuicksend') - docs
: 0;
const subscriptionCls = new Parse.Object('contracts_Subscriptions');
subscriptionCls.id = resSub.id;
if (updateApiCount > 0) {
subscriptionCls.set('AllowedQuicksend', updateApiCount);
} else {
subscriptionCls.set('AllowedQuicksend', 0);
}
const resSubcription = await subscriptionCls.save(null, { useMasterKey: true });
}
} catch (err) {
console.log('Err in deduct in quick send', err);
}
}
async function sendMail(document, sessionToken) {
const baseUrl = new URL(process.env.PUBLIC_URL);
@@ -90,7 +118,6 @@ export default async function createBatchDocs(request) {
const sessionToken = request.headers['sessiontoken'];
const Documents = JSON.parse(strDocuments);
const Ip = request?.headers?.['x-real-ip'] || '';
// console.log('Documents ', Documents);
const parseConfig = {
baseURL: serverUrl, //localStorage.getItem('baseUrl'),
headers: {
@@ -100,84 +127,121 @@ export default async function createBatchDocs(request) {
},
};
try {
const requests = Documents.map(x => {
const Signers = x.Signers;
const allSigner = x?.Placeholders?.map(
item => Signers?.find(e => item?.signerPtr?.objectId === e?.objectId) || item?.signerPtr
).filter(signer => Object.keys(signer).length > 0);
const date = new Date();
const isoDate = date.toISOString();
let Acl = { [x.CreatedBy.objectId]: { read: true, write: true } };
if (allSigner && allSigner.length > 0) {
allSigner.forEach(x => {
const obj = { [x.CreatedBy.objectId]: { read: true, write: true } };
Acl = { ...Acl, ...obj };
});
}
return {
method: 'POST',
path: '/app/classes/contracts_Document',
body: {
Name: x.Name,
URL: x.URL,
Note: x.Note,
Description: x.Description,
CreatedBy: x.CreatedBy,
SendinOrder: x.SendinOrder || true,
ExtUserPtr: {
__type: 'Pointer',
className: x.ExtUserPtr.className,
objectId: x.ExtUserPtr.objectId,
},
Placeholders: x.Placeholders.map(y =>
y?.signerPtr?.objectId
? {
...y,
signerPtr: {
__type: 'Pointer',
className: 'contracts_Contactbook',
objectId: y.signerPtr.objectId,
},
signerObjId: y.signerObjId,
}
: { ...y, signerPtr: {}, signerObjId: '' }
),
SignedUrl: x.URL || x.SignedUrl,
SentToOthers: true,
Signers: allSigner?.map(y => ({
__type: 'Pointer',
className: 'contracts_Contactbook',
objectId: y.objectId,
})),
ACL: Acl,
SentToOthers: true,
RemindOnceInEvery: x.RemindOnceInEvery || 5,
AutomaticReminders: x.AutomaticReminders || false,
TimeToCompleteDays: x.TimeToCompleteDays || 15,
OriginIp: Ip,
DocSentAt: { __type: 'Date', iso: isoDate },
},
};
const user = await axios.get(serverUrl + '/users/me', {
headers: {
'X-Parse-Application-Id': appId,
'X-Parse-Session-Token': request.headers['sessiontoken'],
},
});
// console.log('requests ', requests);
if (user.data) {
const extCls = new Parse.Query('contracts_Users');
extCls.equalTo('UserId', {
__type: 'Pointer',
className: '_User',
objectId: user.data.objectId,
});
const resExt = await extCls.first({ useMasterKey: true });
if (resExt) {
const _resExt = JSON.parse(JSON.stringify(resExt));
console.log('here');
try {
const requests = Documents.map(x => {
const Signers = x.Signers;
const allSigner = x?.Placeholders?.map(
item =>
Signers?.find(e => item?.signerPtr?.objectId === e?.objectId) || item?.signerPtr
).filter(signer => Object.keys(signer).length > 0);
const date = new Date();
const isoDate = date.toISOString();
let Acl = { [x.CreatedBy.objectId]: { read: true, write: true } };
if (allSigner && allSigner.length > 0) {
allSigner.forEach(x => {
const obj = { [x.CreatedBy.objectId]: { read: true, write: true } };
Acl = { ...Acl, ...obj };
});
}
return {
method: 'POST',
path: '/app/classes/contracts_Document',
body: {
Name: x.Name,
URL: x.URL,
Note: x.Note,
Description: x.Description,
CreatedBy: x.CreatedBy,
SendinOrder: x.SendinOrder || true,
ExtUserPtr: {
__type: 'Pointer',
className: x.ExtUserPtr.className,
objectId: x.ExtUserPtr.objectId,
},
Placeholders: x.Placeholders.map(y =>
y?.signerPtr?.objectId
? {
...y,
signerPtr: {
__type: 'Pointer',
className: 'contracts_Contactbook',
objectId: y.signerPtr.objectId,
},
signerObjId: y.signerObjId,
}
: { ...y, signerPtr: {}, signerObjId: '' }
),
SignedUrl: x.URL || x.SignedUrl,
SentToOthers: true,
Signers: allSigner?.map(y => ({
__type: 'Pointer',
className: 'contracts_Contactbook',
objectId: y.objectId,
})),
ACL: Acl,
SentToOthers: true,
RemindOnceInEvery: x.RemindOnceInEvery || 5,
AutomaticReminders: x.AutomaticReminders || false,
TimeToCompleteDays: x.TimeToCompleteDays || 15,
OriginIp: Ip,
DocSentAt: { __type: 'Date', iso: isoDate },
},
};
});
// console.log('requests ', requests);
const response = await axios.post('batch', { requests: requests }, parseConfig);
// // Handle the batch query response
// console.log('Batch query response:', response.data);
if (response.data && response.data.length > 0) {
const updateDocuments = Documents.map((x, i) => ({
...x,
objectId: response.data[i]?.success?.objectId,
createdAt: response.data[i]?.success?.createdAt,
}));
for (let i = 0; i < updateDocuments.length; i++) {
sendMail(updateDocuments[i], sessionToken);
const response = await axios.post('batch', { requests: requests }, parseConfig);
// // Handle the batch query response
// console.log('Batch query response:', response.data);
if (response.data && response.data.length > 0) {
const updateDocuments = Documents.map((x, i) => ({
...x,
objectId: response.data[i]?.success?.objectId,
createdAt: response.data[i]?.success?.createdAt,
}));
deductcount(_resExt.TenantId.objectId, response.data.length);
for (let i = 0; i < updateDocuments.length; i++) {
sendMail(updateDocuments[i], sessionToken);
}
return 'success';
}
// Handle individual responses within response.data.results
} catch (error) {
const code = err?.response?.data?.code || err?.response?.status || err?.code || 400;
const msg =
err?.response?.data?.error ||
err?.response?.data ||
err?.message ||
'Something went wrong.';
console.log('Error performing batch query:', code, msg);
throw new Parse.Error(code, msg);
}
}
return 'success';
} else {
new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'User not found.');
}
// Handle individual responses within response.data.results
} catch (error) {
console.error('Error performing batch query:', error);
} catch (err) {
console.log('err in createbatchdoc', err);
const code = err?.code || 400;
const msg = err?.message || 'Something went wrong.';
new Parse.Error(code, msg);
}
}