diff --git a/apps/OpenSign/moduleFederation.config.js b/apps/OpenSign/moduleFederation.config.js index 5324d4c8c..9ba314cd1 100644 --- a/apps/OpenSign/moduleFederation.config.js +++ b/apps/OpenSign/moduleFederation.config.js @@ -20,10 +20,6 @@ module.exports = { "react-router-dom": { singleton: true, requiredVersion: dependencies["react-router-dom"] - }, - "rjsf-conditionals": { - singleton: true, - requiredVersion: dependencies["rjsf-conditionals"] } } }; diff --git a/apps/OpenSign/package-lock.json b/apps/OpenSign/package-lock.json index 4832ae0ee..a4c879102 100644 --- a/apps/OpenSign/package-lock.json +++ b/apps/OpenSign/package-lock.json @@ -9,9 +9,6 @@ "version": "0.1.0", "dependencies": { "@reduxjs/toolkit": "^1.9.7", - "@rjsf/core": "^5.13.0", - "@rjsf/utils": "^5.13.0", - "@rjsf/validator-ajv8": "^5.13.0", "axios": "^1.5.1", "daisyui": "^3.9.2", "file-saver": "^2.0.5", @@ -39,7 +36,6 @@ "reactour": "^1.19.2", "redux": "^4.2.1", "redux-thunk": "^2.4.2", - "rjsf-conditionals": "github:prafullnavkar-nxg/rjsf-conditionals", "serve": "^14.2.1", "styled-components": "^4.4.1", "web-vitals": "^2.1.4" @@ -3921,85 +3917,6 @@ "react": ">=16.14.0" } }, - "node_modules/@rjsf/core": { - "version": "5.13.0", - "resolved": "https://registry.npmjs.org/@rjsf/core/-/core-5.13.0.tgz", - "integrity": "sha512-rCpJGR0yPP/ip9LKcr3SmDMkbLx4QIaRA+ag0rcalSw1XLXBSzh53SpfgaB2HN++1xhUvWtIUERRHpWjQp1E7w==", - "dependencies": { - "lodash": "^4.17.21", - "lodash-es": "^4.17.21", - "markdown-to-jsx": "^7.3.2", - "nanoid": "^3.3.6", - "prop-types": "^15.8.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@rjsf/utils": "^5.12.x", - "react": "^16.14.0 || >=17" - } - }, - "node_modules/@rjsf/utils": { - "version": "5.13.0", - "resolved": "https://registry.npmjs.org/@rjsf/utils/-/utils-5.13.0.tgz", - "integrity": "sha512-tG2OuOJUJZ0W7VMZceD0I2SOjfMRRT1tRtG+SKbdNqhtH/gpg40aOMUj9cWgSQnYISEkNZjZq/z7NWln5RxW6A==", - "dependencies": { - "json-schema-merge-allof": "^0.8.1", - "jsonpointer": "^5.0.1", - "lodash": "^4.17.21", - "lodash-es": "^4.17.21", - "react-is": "^18.2.0" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "react": "^16.14.0 || >=17" - } - }, - "node_modules/@rjsf/utils/node_modules/react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" - }, - "node_modules/@rjsf/validator-ajv8": { - "version": "5.13.0", - "resolved": "https://registry.npmjs.org/@rjsf/validator-ajv8/-/validator-ajv8-5.13.0.tgz", - "integrity": "sha512-8j0xLsxJA/k1UADeDYZ2aMVrswvOCEYNC++YchoAgWRHqDiaGAUyRbbk7oxMi6QUXnhnlCIepzNeTclHnSfPXQ==", - "dependencies": { - "ajv": "^8.12.0", - "ajv-formats": "^2.1.1", - "lodash": "^4.17.21", - "lodash-es": "^4.17.21" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@rjsf/utils": "^5.12.x" - } - }, - "node_modules/@rjsf/validator-ajv8/node_modules/ajv": { - "version": "8.12.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", - "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@rjsf/validator-ajv8/node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" - }, "node_modules/@rollup/plugin-babel": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz", @@ -6965,27 +6882,6 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, - "node_modules/compute-gcd": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/compute-gcd/-/compute-gcd-1.2.1.tgz", - "integrity": "sha512-TwMbxBNz0l71+8Sc4czv13h4kEqnchV9igQZBi6QUaz09dnz13juGnnaWWJTRsP3brxOoxeB4SA2WELLw1hCtg==", - "dependencies": { - "validate.io-array": "^1.0.3", - "validate.io-function": "^1.0.2", - "validate.io-integer-array": "^1.0.0" - } - }, - "node_modules/compute-lcm": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/compute-lcm/-/compute-lcm-1.1.2.tgz", - "integrity": "sha512-OFNPdQAXnQhDSKioX8/XYT6sdUlXwpeMjfd6ApxMJfyZ4GxmLR1xvMERctlYhlHwIiz6CSpBc2+qYKjHGZw4TQ==", - "dependencies": { - "compute-gcd": "^1.2.1", - "validate.io-array": "^1.0.3", - "validate.io-function": "^1.0.2", - "validate.io-integer-array": "^1.0.0" - } - }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -7676,14 +7572,6 @@ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==" }, - "node_modules/deepcopy": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/deepcopy/-/deepcopy-2.1.0.tgz", - "integrity": "sha512-8cZeTb1ZKC3bdSCP6XOM1IsTczIO73fdqtwa2B0N15eAz7gmyhQo+mc5gnFuulsgN3vIQYmTgbmQVKalH1dKvQ==", - "dependencies": { - "type-detect": "^4.0.8" - } - }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", @@ -13418,27 +13306,6 @@ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" }, - "node_modules/json-schema-compare": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/json-schema-compare/-/json-schema-compare-0.2.2.tgz", - "integrity": "sha512-c4WYmDKyJXhs7WWvAWm3uIYnfyWFoIp+JEoX34rctVvEkMYCPGhXtvmFFXiffBbxfZsvQ0RNnV5H7GvDF5HCqQ==", - "dependencies": { - "lodash": "^4.17.4" - } - }, - "node_modules/json-schema-merge-allof": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/json-schema-merge-allof/-/json-schema-merge-allof-0.8.1.tgz", - "integrity": "sha512-CTUKmIlPJbsWfzRRnOXz+0MjIqvnleIXwFTzz+t9T86HnYX/Rozria6ZVGLktAU9e+NygNljveP+yxqtQp/Q4w==", - "dependencies": { - "compute-lcm": "^1.1.2", - "json-schema-compare": "^0.2.2", - "lodash": "^4.17.20" - }, - "engines": { - "node": ">=12.0.0" - } - }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -13934,21 +13801,11 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, - "node_modules/lodash-es": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz", - "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==" - }, "node_modules/lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==" }, - "node_modules/lodash.isequalwith": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.isequalwith/-/lodash.isequalwith-4.4.0.tgz", - "integrity": "sha512-dcZON0IalGBpRmJBmMkaoV7d3I80R2O+FrzsZyHdNSFrANq/cgDqKQNmAHE8UEj4+QYWwwhkQOVdLHiAopzlsQ==" - }, "node_modules/lodash.isplainobject": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", @@ -14310,17 +14167,6 @@ "tmpl": "1.0.5" } }, - "node_modules/markdown-to-jsx": { - "version": "7.3.2", - "resolved": "https://registry.npmjs.org/markdown-to-jsx/-/markdown-to-jsx-7.3.2.tgz", - "integrity": "sha512-B+28F5ucp83aQm+OxNrPkS8z0tMKaeHiy0lHJs3LqCyDQFtWuenaIrkaVTgAm1pf1AU85LXltva86hlaT17i8Q==", - "engines": { - "node": ">= 10" - }, - "peerDependencies": { - "react": ">= 0.14.0" - } - }, "node_modules/mdn-data": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.4.tgz", @@ -18202,26 +18048,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/rjsf-conditionals": { - "version": "1.5.0", - "resolved": "git+ssh://git@github.com/prafullnavkar-nxg/rjsf-conditionals.git#439aa44e3ece077b1c8098278f86f454ad7185cf", - "license": "Apache-2.0", - "dependencies": { - "@rjsf/validator-ajv8": "^5.13.0", - "deepcopy": "^2.0.0", - "lodash.isequalwith": "^4.4.0", - "selectn": "^1.1.2" - }, - "engines": { - "node": ">=10" - }, - "peerDependencies": { - "@rjsf/core": ">=2.0.0", - "core-js": "^2.5.7", - "prop-types": "^15.7.2", - "react": "^18.2.0" - } - }, "node_modules/rollup": { "version": "2.79.1", "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.1.tgz", @@ -20423,38 +20249,6 @@ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==" }, - "node_modules/validate.io-array": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/validate.io-array/-/validate.io-array-1.0.6.tgz", - "integrity": "sha512-DeOy7CnPEziggrOO5CZhVKJw6S3Yi7e9e65R1Nl/RTN1vTQKnzjfvks0/8kQ40FP/dsjRAOd4hxmJ7uLa6vxkg==" - }, - "node_modules/validate.io-function": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/validate.io-function/-/validate.io-function-1.0.2.tgz", - "integrity": "sha512-LlFybRJEriSuBnUhQyG5bwglhh50EpTL2ul23MPIuR1odjO7XaMLFV8vHGwp7AZciFxtYOeiSCT5st+XSPONiQ==" - }, - "node_modules/validate.io-integer": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/validate.io-integer/-/validate.io-integer-1.0.5.tgz", - "integrity": "sha512-22izsYSLojN/P6bppBqhgUDjCkr5RY2jd+N2a3DCAUey8ydvrZ/OkGvFPR7qfOpwR2LC5p4Ngzxz36g5Vgr/hQ==", - "dependencies": { - "validate.io-number": "^1.0.3" - } - }, - "node_modules/validate.io-integer-array": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/validate.io-integer-array/-/validate.io-integer-array-1.0.0.tgz", - "integrity": "sha512-mTrMk/1ytQHtCY0oNO3dztafHYyGU88KL+jRxWuzfOmQb+4qqnWmI+gykvGp8usKZOM0H7keJHEbRaFiYA0VrA==", - "dependencies": { - "validate.io-array": "^1.0.3", - "validate.io-integer": "^1.0.4" - } - }, - "node_modules/validate.io-number": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/validate.io-number/-/validate.io-number-1.0.3.tgz", - "integrity": "sha512-kRAyotcbNaSYoDnXvb4MHg/0a1egJdLwS6oJ38TJY7aw9n93Fl/3blIXdyYvPOp55CNxywooG/3BcrwNrBpcSg==" - }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", diff --git a/apps/OpenSign/package.json b/apps/OpenSign/package.json index d18085126..edffdbc62 100644 --- a/apps/OpenSign/package.json +++ b/apps/OpenSign/package.json @@ -4,9 +4,6 @@ "private": true, "dependencies": { "@reduxjs/toolkit": "^1.9.7", - "@rjsf/core": "^5.13.0", - "@rjsf/utils": "^5.13.0", - "@rjsf/validator-ajv8": "^5.13.0", "axios": "^1.5.1", "daisyui": "^3.9.2", "file-saver": "^2.0.5", @@ -34,7 +31,6 @@ "reactour": "^1.19.2", "redux": "^4.2.1", "redux-thunk": "^2.4.2", - "rjsf-conditionals": "github:prafullnavkar-nxg/rjsf-conditionals", "serve": "^14.2.1", "styled-components": "^4.4.1", "web-vitals": "^2.1.4" diff --git a/apps/OpenSign/src/components/AddUser.js b/apps/OpenSign/src/components/AddUser.js new file mode 100644 index 000000000..5861f6be6 --- /dev/null +++ b/apps/OpenSign/src/components/AddUser.js @@ -0,0 +1,283 @@ +import React, { useState } from "react"; +import Parse from "parse"; +import axios from "axios"; +import Title from "./Title"; +import Alert from "../primitives/Alert"; + +const AddUser = (props) => { + const [name, setName] = useState(""); + const [phone, setPhone] = useState(""); + const [email, setEmail] = useState(""); + const [isLoader, setIsLoader] = useState(false); + const [isUserExist, setIsUserExist] = useState(false); + const parseBaseUrl = localStorage.getItem("baseUrl"); + const parseAppId = localStorage.getItem("parseAppId"); + Parse.serverURL = parseBaseUrl; + Parse.initialize(parseAppId); + + const checkUserExist = async () => { + try { + const res = await Parse.Cloud.run("getUserDetails", { + email: email, + userId: Parse.User.current().id + }); + if (res) { + return true; + } else { + return false; + } + } catch (err) { + console.log("err", err); + } + }; + // Define a function to handle form submission + const handleSubmit = async (e) => { + e.preventDefault(); + e.stopPropagation(); + setIsLoader(true); + const res = await checkUserExist(); + if (res) { + setIsUserExist(true); + setIsLoader(false); + setTimeout(() => { + setIsUserExist(false); + }, 1000); + } else { + try { + const contactQuery = new Parse.Object("contracts_Users"); + contactQuery.set("Name", name); + contactQuery.set("Phone", phone); + contactQuery.set("Email", email); + contactQuery.set("UserRole", "contracts_User"); + + if (localStorage.getItem("TenetId")) { + contactQuery.set("TenantId", { + __type: "Pointer", + className: "partners_Tenant", + objectId: localStorage.getItem("TenetId") + }); + } + + 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("phone", phone); + _user.set("password", phone); + + const user = await _user.save(); + if (user) { + const roleurl = `${parseBaseUrl}functions/AddUserToRole`; + const headers = { + "Content-Type": "application/json", + "X-Parse-Application-Id": parseAppId, + sessionToken: localStorage.getItem("accesstoken") + }; + const body = { + appName: localStorage.getItem("_appName"), + roleName: "contracts_User", + userId: user.id + }; + await axios.post(roleurl, body, { headers: headers }); + const currentUser = Parse.User.current(); + contactQuery.set( + "CreatedBy", + Parse.User.createWithoutData(currentUser.id) + ); + + contactQuery.set("UserId", user); + const acl = new Parse.ACL(); + acl.setPublicReadAccess(true); + acl.setPublicWriteAccess(true); + acl.setReadAccess(currentUser.id, true); + acl.setWriteAccess(currentUser.id, true); + + contactQuery.setACL(acl); + + const res = await contactQuery.save(); + + const parseData = JSON.parse(JSON.stringify(res)); + if (props.details) { + props.details({ + value: parseData[props.valueKey], + label: parseData[props.displayKey] + }); + } + if (props.closePopup) { + props.closePopup(); + } + if (props.handleUserData) { + props.handleUserData(parseData); + } + + setIsLoader(false); + + setName(""); + setPhone(""); + setEmail(""); + } + } catch (err) { + console.log("err ", err); + if (err.code === 202) { + const params = { email: email }; + const userRes = await Parse.Cloud.run("getUserId", params); + const roleurl = `${parseBaseUrl}functions/AddUserToRole`; + const headers = { + "Content-Type": "application/json", + "X-Parse-Application-Id": parseAppId, + sessionToken: localStorage.getItem("accesstoken") + }; + const body = { + appName: localStorage.getItem("_appName"), + roleName: "contracts_User", + userId: userRes.id + }; + await axios.post(roleurl, body, { headers: headers }); + const currentUser = Parse.User.current(); + contactQuery.set( + "CreatedBy", + Parse.User.createWithoutData(currentUser.id) + ); + + contactQuery.set("UserId", { + __type: "Pointer", + className: "_User", + objectId: userRes.id + }); + const acl = new Parse.ACL(); + acl.setPublicReadAccess(true); + acl.setPublicWriteAccess(true); + acl.setReadAccess(currentUser.id, true); + acl.setWriteAccess(currentUser.id, true); + + contactQuery.setACL(acl); + const res = await contactQuery.save(); + + const parseData = JSON.parse(JSON.stringify(res)); + if (props.details) { + props.details({ + value: parseData[props.valueKey], + label: parseData[props.displayKey] + }); + } + if (props.closePopup) { + props.closePopup(); + } + if (props.handleUserData) { + props.handleUserData(parseData); + } + setIsLoader(false); + setName(""); + setPhone(""); + setEmail(""); + } + } + } catch (err) { + // console.log("err", err); + setIsLoader(false); + alert("something went wrong!"); + } + } + }; + + // Define a function to handle the "add yourself" checkbox + const handleReset = () => { + setName(""); + setPhone(""); + setEmail(""); + }; + + return ( +
+ + {isUserExist && <Alert type="danger">User already exists!</Alert>} + {isLoader && ( + <div className="fixed inset-0 flex justify-center items-center bg-black bg-opacity-30 z-50"> + <div + style={{ + fontSize: "45px", + color: "#3dd3e0" + }} + className="loader-37" + ></div> + </div> + )} + <div className="w-full mx-auto"> + <form onSubmit={handleSubmit}> + <h1 className="text-[20px] font-semibold mb-4">Add User</h1> + <div className="mb-3"> + <label + htmlFor="name" + className="block text-xs text-gray-700 font-semibold" + > + Name + <span style={{ color: "red", fontSize: 13 }}> *</span> + </label> + <input + type="text" + id="name" + value={name} + onChange={(e) => setName(e.target.value)} + required + className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + /> + </div> + <div className="mb-3"> + <label + htmlFor="email" + className="block text-xs text-gray-700 font-semibold" + > + Email + <span style={{ color: "red", fontSize: 13 }}> *</span> + </label> + <input + type="email" + id="email" + value={email} + onChange={(e) => setEmail(e.target.value)} + required + className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + /> + </div> + <div className="mb-3"> + <label + htmlFor="phone" + className="block text-xs text-gray-700 font-semibold" + > + Phone + <span style={{ color: "red", fontSize: 13 }}> *</span> + </label> + <input + type="text" + id="phone" + value={phone} + onChange={(e) => setPhone(e.target.value)} + required + className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + /> + </div> + + <div className="flex items-center mt-3 gap-2 text-white"> + <button + type="submit" + className="bg-[#1ab6ce] rounded-sm shadow-md text-[13px] font-semibold uppercase text-white py-1.5 px-2.5 focus:outline-none" + > + Submit + </button> + <div + type="button" + onClick={() => handleReset()} + className="bg-[#188ae2] rounded-sm shadow-md text-[13px] font-semibold uppercase text-white py-1.5 px-2.5 text-center ml-[2px] focus:outline-none" + > + Reset + </div> + </div> + </form> + </div> + </div> + ); +}; + +export default AddUser; diff --git a/apps/OpenSign/src/components/TreeEditForm.js b/apps/OpenSign/src/components/TreeEditForm.js deleted file mode 100644 index 4de7e9c2f..000000000 --- a/apps/OpenSign/src/components/TreeEditForm.js +++ /dev/null @@ -1,391 +0,0 @@ -import React, { useState, useEffect } from "react"; -import Form from "@rjsf/core"; -import validator from "@rjsf/validator-ajv8"; -import Parse from "parse"; -import "../styles/loader.css"; -import LayoutField from "./fields/Rjsf-layout"; -import TimeWidget from "./fields/TimeWidget"; -import Level1Dropdown from "./fields/Level1Dropdown"; -import HiddenField from "./fields/HiddenField"; -import MultiSelectField from "./fields/MultiSelectField"; -import TreeWidget from "../components/TreeWidget"; -import { formJson } from "../json/FormJson"; -const TreeEditForm = (props) => { - const widget = { - TimeWidget: TimeWidget - }; - const fields = { - layout: LayoutField, - Level1Dropdown: Level1Dropdown, - HiddenField: HiddenField, - MultiSelectField: MultiSelectField, - FolderComponent: TreeWidget - }; - - const [schema, setschema] = useState({}); - const [ui_schema, setui_schema] = useState({}); - const [title, settitle] = useState(""); - const [schemaState, setschemaState] = useState({}); - const [formData, setformData] = useState({}); - const [active, setactive] = useState(true); - const [loading, setloading] = useState(false); - const [_validate, set_validate] = useState(null); - const [noValidate, setnoValidate] = useState(false); - const [parseBaseUrl] = useState(localStorage.getItem("baseUrl")); - const [parseAppId] = useState(localStorage.getItem("parseAppId")); - - const getForm = async (id) => { - setloading(true); - try { - //get json form data (schema ,uischema) - const results = formJson(id); - try { - let _record = Parse.Object.extend(results.class); - var query1 = new Parse.Query(_record); - await query1.get(props.objectId).then( - (x) => { - try { - if (x) { - let result = x.toJSON(); - let new_result = result; - for (let [key, value] of Object.entries(result)) { - if (value["__type"] === "Date") { - let todayTime1 = new Date(value.iso); - var month = String(todayTime1.getMonth() + 1); - var day = String(todayTime1.getDate()); - var year = String(todayTime1.getFullYear()); - if (month.length < 2) month = "0" + month; - if (day.length < 2) day = "0" + day; - let date1 = year + "-" + month + "-" + day; - let bindVar = date1; - if (!results.jsonSchema.properties[key].format) { - bindVar = todayTime1.toISOString(); - } - new_result[key] = bindVar; - } - } - setschemaState(results.jsonSchema); - setformData(new_result); - } - } catch (error) { - //alert(error.message); - - setloading(false); - } - }, - (error) => { - console.log("err", error); - setloading(false); - } - ); - setschema(results.jsonSchema); - setui_schema(results.uiSchema); - set_validate(results.validFunction); - setnoValidate(results.noValidate); - settitle(results.class); - setloading(false); - setactive(true); - } catch (error) { - setloading(false); - } - } catch (e) { - setloading(false); - console.error("Problem", e); - } - }; - - const wrap = (s) => "{ return " + s + " };"; - - const dynamicValidate = (formData, errors) => { - try { - let body = atob(_validate); - let res = new Function(wrap(body)) - .call(null) - .call(null, formData, errors); - return res; - } catch (error) { - console.log(error); - } - }; - - const handleSubmit = async ({ formData }) => { - setactive(false); - setloading(true); - let RowData = formData; - RowData && - Object.entries(RowData).forEach(([key, value]) => { - if (typeof value === "string") { - RowData[key] = value.trim(); - } - }); - let _scanData = schemaState; - if (_scanData.dependencies) { - Object.keys(_scanData.dependencies).forEach((key) => { - if (_scanData.dependencies[key].oneOf) { - _scanData.dependencies[key].oneOf.forEach((val) => { - Object.keys(val.properties).forEach((k) => { - if (typeof val.properties[k] === "object") { - if (val.properties[k].format === "date") { - if (RowData[k]) { - let newdate = new Date(RowData[k]); - RowData[k] = newdate; - } - } - if (val.properties[k].component === "HtmlEditor") { - if (RowData[k]) { - let newHtml = RowData[k] - .replace(/<p[^>]*>/g, "") - .replace(/<\/p>/g, " "); - RowData[k] = newHtml; - } - } - if (val.properties[k].component === "DateTime") { - if (RowData[k]) { - let newDate11 = new Date(RowData[k]); - RowData[k] = newDate11; - } - } - if (val.properties[k].component === "CurrencyInput") { - if (val.properties[k].currencyColumn) { - RowData[`${val.properties[k].currencyColumn}`] = - val.properties[k].defaultcurrency; - } - } - if (val.properties[k].type === "string") { - if (typeof RowData[k] === "string") - RowData[k] = RowData[k].trim(); - } - if (val.properties[k].data !== undefined) { - if (val.properties[k].data.isPointer) { - let pointer = undefined; - if (val.properties[k].data.class) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: val.properties[k].data.class, - objectId: RowData[k] - }; - } - } else { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: localStorage.getItem("extended_class"), - objectId: RowData[k] - }; - } - } - RowData[k] = pointer; - } - if (val.properties[k].data.FolderTypeValue) { - if (RowData[k]) { - let obj = { - __type: "Pointer", - className: val.properties[k].data.ClassName, - objectId: RowData[k] - }; - RowData[k] = obj; - } - } - } - } - }); - }); - } - }); - } - let temp = []; - - let _dd = _scanData.properties; - let allowed = []; - if (_dd) { - Object.keys(_dd).forEach(function (k) { - allowed.push(k); - if (RowData[k]) { - let pointer = { - __type: "Pointer", - className: _dd[k].class, - objectId: RowData[k] - }; - RowData[k] = pointer; - } - if (_dd[k].format === "date") { - if (RowData[k]) { - let newdate = new Date(RowData[k]); - if (!isNaN(newdate.getTime())) { - RowData[k] = newdate; - } - } - } - if (_dd[k].component === "HtmlEditor") { - if (RowData[k]) { - let newHtml = RowData[k] - .replace(/<p[^>]*>/g, "") - .replace(/<\/p>/g, " "); - RowData[k] = newHtml; - } - } - if (_dd[k].component === "DateTime") { - if (RowData[k]) { - let newdate = new Date(RowData[k]); - if (!isNaN(newdate.getTime())) { - RowData[k] = newdate; - } - } - } - if (_dd[k].format === "date-time") { - let newdate = new Date(RowData[k]); - RowData[k] = newdate; - } - if (_dd[k].component === "CurrencyInput") { - if (_dd[k].currencyColumn) { - RowData[`${_dd[k].currencyColumn}`] = _dd[k].defaultcurrency; - } - } - if (_dd[k].data !== undefined) { - if (_dd[k].data.isPointer) { - let pointer = undefined; - if (typeof RowData[k] === "object") { - if (RowData[k]) { - if (RowData[k].objectId !== "Select") { - let obj = { - __type: "Pointer", - className: RowData[k].className, - objectId: RowData[k].objectId - }; - pointer = obj; - } - } - } else if (_dd[k].data.class) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: _dd[k].data.class, - objectId: RowData[k] - }; - } - } else { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: localStorage.getItem("extended_class"), - objectId: RowData[k] - }; - } - } - - RowData[k] = pointer; - } - if (_dd[k].data.FolderTypeValue) { - if (RowData[k]) { - let obj = { - __type: "Pointer", - className: _dd[k].data.ClassName, - objectId: RowData[k] - }; - RowData[k] = obj; - } - } - } - if (_dd[k].type === "string") { - if (typeof RowData[k] === "string") RowData[k] = RowData[k].trim(); - } - }); - } - const filtered = Object.keys(RowData) - .filter((key) => allowed.includes(key)) - .reduce((obj, key) => { - obj[key] = RowData[key]; - return obj; - }, {}); - - try { - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - const currentUser = Parse.User.current(); - if (temp.length !== 0) { - let userPointer = { - __type: "Pointer", - className: "_User", - objectId: currentUser.id - }; - filtered[[temp[0]]] = userPointer; - } - var data = Parse.Object.extend(title); - var query = new Parse.Query(data); - query.get(props.objectId).then(async (object) => { - object.save(filtered).then( - () => { - try { - alert("Record updated successfully"); - props.HideView(false); - setloading(false); - setactive(true); - } catch (error) { - console.log("err", error); - } - }, - (error) => { - console.log("err", error); - setloading(false); - setactive(true); - } - ); - }); - } catch (error) { - console.log("err", error); - - alert(error.message); - setloading(false); - setactive(true); - } - }; - - useEffect(() => { - if (props.FormId) { - getForm(props.FormId); - } - // eslint-disable-next-line - }, [props.FormId]); - - if (loading) { - return ( - <div - className="loader-01" - style={{ - marginTop: "50px", - marginLeft: "50%", - color: "rgb(0,28,28)", - fontSize: "35px" - }} - ></div> - ); - } - return ( - <Form - schema={schema} - uiSchema={ui_schema} - formData={formData} - showErrorList={false} - widgets={widget} - fields={fields} - validate={noValidate && dynamicValidate} - onSubmit={handleSubmit} - validator={validator} - > - <div> - {active ? ( - <button className="bg-[#1ab6ce] px-3 py-2 rounded text-white text-sm" type="submit"> - Update - </button> - ) : ( - <button className="bg-[#1ab6ce] px-3 py-2 rounded text-white text-sm" type="submit" disabled> - Update - </button> - )} - </div> - </Form> - ); -}; - -export default TreeEditForm; diff --git a/apps/OpenSign/src/components/TreeFormComponent.js b/apps/OpenSign/src/components/TreeFormComponent.js deleted file mode 100644 index 7f7ad806c..000000000 --- a/apps/OpenSign/src/components/TreeFormComponent.js +++ /dev/null @@ -1,237 +0,0 @@ -import React, { useEffect, useState } from "react"; -import Form from "@rjsf/core"; -import validator from "@rjsf/validator-ajv8"; -import LayoutField from "./fields/Rjsf-layout"; -import Level1Dropdown from "./fields/Level1Dropdown"; -import HiddenField from "./fields/HiddenField"; -import MultiSelectField from "./fields/MultiSelectField"; -import "../styles/loader.css"; -import "../styles/form.css"; -import FileUpload from "./fields/FileUpload"; -import parse from "html-react-parser"; -import TimeWidget from "./fields/TimeWidget"; -import { formJson } from "../json/FormJson"; -function TreeFormComponent(props) { - const widget = { - TimeWidget: TimeWidget - }; - - const fields = { - layout: LayoutField, - FileUpload: FileUpload, - Level1Dropdown: Level1Dropdown, - HiddenField: HiddenField, - MultiSelectField: MultiSelectField - }; - - const [link, setLink] = useState(""); - const [help, setHelp] = useState(""); - const toastDescription = ""; - const toastColor = "#5cb85c"; - const [loading, setLoding] = useState(true); - const [schemaState, setSchemaState] = useState({}); - const [formData, setFormData] = useState({}); - const [ui_schema, setUi_schema] = useState({}); - const active = true; - - console.log("new form", props); - - const getForm = async (id) => { - setLoding(true); - try { - // get json from data(jsonschema, uischema) - const results = formJson(id); - // console.log("result", results); - if (results) { - let parentObject = {}, - childObject = {}; - const resultjson = results; - for (let [key, value] of Object.entries( - resultjson.jsonSchema.properties - )) { - if (key === props.ParentField) { - if (props.ParentValue[key]) { - parentObject = { [key]: props.ParentValue[key] }; - } - } else { - if (props.ParentValue && typeof props.ParentValue === "object") { - Object.entries(props.ParentValue).forEach(([k, value]) => { - if (k === key) { - let newO = { [k]: value }; - parentObject = { ...parentObject, ...newO }; - } - }); - } - } - if (props.ChildField) { - Object.entries(props.ChildField).forEach(([k, value]) => { - if (k === key) { - let newO = { [k]: value }; - childObject = { ...childObject, ...newO }; - } - }); - } - - if (typeof value === "object") { - for (let [k, v] of Object.entries(value)) { - if (k === "format" && v === "date") { - let today = new Date(); - let date = - today.getFullYear() + - "-" + - ("0" + (today.getMonth() + 1)).slice(-2) + - "-" + - ("0" + today.getDate()).slice(-2); - value.default = date; - } - } - } - } - if (props.ParentField) { - setFormData({ ...parentObject, ...childObject }); - } - - let txt, link; - if (resultjson.help) { - if (resultjson.help.htmlbody) { - txt = resultjson.help.htmlbody; - } - if (resultjson.help.link) { - link = resultjson.help.link; - } - } - setHelp(txt); - setLink(link); - - props.ClassName(resultjson.class); - props.SchemaState(resultjson.jsonSchema); - setSchemaState(resultjson.jsonSchema); - setUi_schema(resultjson.uiSchema); - setLoding(false); - } else { - alert("form not found"); - setLoding(false); - } - } catch (e) { - console.error("Problem", e); - setLoding(false); - } - }; - - useEffect(() => { - if (!props.IsEdit) { - getForm(props.Id); - } - // console.log("props tree", props); - // eslint-disable-next-line - }, []); - - let formView = ( - <React.Fragment> - <Form - schema={schemaState} - uiSchema={ui_schema} - showErrorList={false} - widgets={widget} - fields={fields} - formData={formData} - onSubmit={props.handleSubmit} - validator={validator} - > - {active ? ( - <button className="btn btn-info submiBtn" type="submit"> - {props.IsEdit ? "update folder" : "create folder"} - </button> - ) : ( - <button className="btn btn-info submiBtn " type="submit" disabled> - submitting... - </button> - )} - </Form> - </React.Fragment> - ); - - if (loading) { - formView = ( - <div style={{ height: "300px" }}> - <div - style={{ - marginLeft: "45%", - marginTop: "150px", - fontSize: "45px", - color: "#3dd3e0" - }} - className="loader-37" - ></div> - </div> - ); - } - - return ( - <React.Fragment> - <div className="row"> - <div className="col-md-12"> - <div className="card"> - <div className="card-body no-padding height-9"> - {help ? ( - <div className="dropdown" style={{ marginTop: "-30px" }}> - <i - className="far fa-question-circle dropdown-toggle hovereffect" - aria-hidden="true" - id="dropdownMenuButton" - data-toggle="dropdown" - aria-haspopup="true" - aria-expanded="false" - style={{ - fontSize: "18px", - color: "purple", - cursor: "pointer !important", - position: "relative", - top: "40px", - left: "98%" - }} - ></i> - <div - className="dropdown-menu" - aria-labelledby="dropdownMenuButton" - style={{ - marginleft: "-121px", - margintop: "-14px", - position: "absolute", - padding: "10px", - width: "300px", - top: "102px!important" - }} - > - {parse(` - ${help} - `)} - <br /> - {link ? ( - <a - onClick={(e) => { - e.preventDefault(); - window.location.href = link; - }} - target="_blank" - className="btn btn-xs btn-primary" - > - Read more.. - </a> - ) : null} - </div> - </div> - ) : null} - <div style={{ fontSize: "13px" }}>{formView}</div> - </div> - </div> - </div> - </div> - <div id="snackbar" style={{ backgroundColor: toastColor }}> - {toastDescription} - </div> - </React.Fragment> - ); -} - -export default TreeFormComponent; diff --git a/apps/OpenSign/src/components/TreeWidget.js b/apps/OpenSign/src/components/TreeWidget.js deleted file mode 100644 index 569112d71..000000000 --- a/apps/OpenSign/src/components/TreeWidget.js +++ /dev/null @@ -1,895 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { connect } from "react-redux"; -import LabelField from "./fields/LabelField"; -import Parse from "parse"; -import axios from "axios"; -import "../styles/spinner.css"; -import TreeFormComponent from "./TreeFormComponent"; -// import TreeEditForm from "./TreeEditForm"; -import "../styles/modal.css"; -import Modal from "react-modal"; - -const TreeWidget = (props) => { - const [parseBaseUrl] = useState(localStorage.getItem("baseUrl")); - const [parseAppId] = useState(localStorage.getItem("parseAppId")); - const [isAddField, setIsAddField] = useState(false); - const [folderList, setFolderList] = useState([]); - const [tabList, setTabList] = useState([]); - const [appId, setAppId] = useState(undefined); - const [selectedFolder, setSelectedFolder] = useState(undefined); - const [loader, setLoader] = useState(false); - const [className, setClassName] = useState(""); - const [schemaState, setSchemaState] = useState({}); - const [TabURL, setTabURL] = useState(""); - const [editable, setEditable] = useState(false); - // const [editId, setEditId] = useState(""); - const [defaultState, setDefaultState] = useState(false); - const [isShowModal, setIsShowModal] = useState(false); - const selectFolderHandle = async () => { - setIsShowModal(true); - setIsAddField(false); - setDefaultState(false); - setFolderList([]); - setLoader(true); - - if (tabList.length > 0) { - let len = tabList.length - 1; - selectedItemList(tabList[len]); - } else { - try { - var test; - if (props.schema.parent) { - try { - if (props.parent[props.schema.parent]) { - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - const currentUser = Parse.User.current(); - let res; - if (localStorage.getItem("Extand_Class")) { - let data = JSON.parse(localStorage.getItem("Extand_Class")); - res = data[0]; - } else { - res = await Parse.Cloud.run("getUserDetails", { - email: currentUser.get("email") - }); - if (res) res = res.toJSON(); - } - if (res) { - let json = res; - setAppId(json.AppId); - } - // eslint-disable-next-line - let reg = /(\#.*?\#)/gi; - let str = props.schema.data.Query; - if (str.includes("#")) { - test = str.replace(reg, props.parent[props.schema.parent]); - } else { - test = str; - } - } else { - if (props.child[props.schema.parent]) { - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - const currentUser = Parse.User.current(); - let res; - if (localStorage.getItem("Extand_Class")) { - let data = JSON.parse(localStorage.getItem("Extand_Class")); - res = data[0]; - } else { - res = await Parse.Cloud.run("getUserDetails", { - email: currentUser.get("email") - }); - if (res) res = res.toJSON(); - } - - if (res) { - let json = res; - setAppId(json.AppId); - } - // eslint-disable-next-line - let reg = /(\#.*?\#)/gi; - let str = props.schema.data.Query; - if (str.includes("#")) { - test = str.replace(reg, props.child[props.schema.parent]); - } else { - test = str; - } - } else { - alert(`Please select ${props.schema.parent}`); - setLoader(false); - return; - } - } - } catch (error) { - console.log("error ", error); - } - } else { - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - const currentUser = Parse.User.current(); - // eslint-disable-next-line - let reg = /(\#.*?\#)/gi; - let str = props.schema.data.Query; - let res; - if (localStorage.getItem("Extand_Class")) { - let data = JSON.parse(localStorage.getItem("Extand_Class")); - res = data[0]; - } else { - // emp = Parse.Object.extend(localStorage.getItem("extended_class")); - // q = new Parse.Query(emp); - // q.equalTo("UserId", currentUser); - // res = await q.first(); - // if (res) res = res.toJSON(); - const currentUser = Parse.User.current(); - res = await Parse.Cloud.run("getUserDetails", { - email: currentUser.get("email") - }); - if (res) res = res.toJSON(); - } - - if (res) { - let json = res; - setAppId(json.AppId); - } - if (str.includes("#")) { - if (res) { - let json = res.toJSON(); - let output = str.match(reg); - if (output.length === 1) { - output = output.join(); - output = output.substring(1, output.length - 1); - output = output.split("."); - if (output.length === 1) { - let out = output[0]; - if (json[out]) { - if (typeof json[out] === "object") { - test = str.replace(reg, JSON.stringify(json[out])); - } else { - test = str.replace(reg, json[out]); - } - } else { - test = str.replace(reg, currentUser.id); - } - } else if (output.length === 2) { - let out1 = json[output[0]][output[1]]; - if (out1) { - test = str.replace(reg, out1); - } - } - } - } - } else { - test = str; - } - } - - let url = `${parseBaseUrl}classes/${props.schema.data.ClassName}?${test}`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - await axios - .get(url, { headers: headers }) - .then((res) => { - if (res) { - setFolderList(res.data.results); - setLoader(false); - } - }) - .catch((err) => { - setLoader(false); - console.log(err); - }); - } catch (error) { - setLoader(false); - } - } - }; - - const selectedItemList = async (folder) => { - setLoader(true); - setFolderList([]); - try { - let url = `${parseBaseUrl}classes/${props.schema.data.ClassName}?where={"${props.schema.data.ParentFolderField}":{"__type":"Pointer","className":"${props.schema.data.ClassName}","objectId":"${folder.objectId}"}}`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - await axios.get(url, { headers: headers }).then((result) => { - if (result) { - setFolderList(result.data.results); - setLoader(false); - } - }); - } catch (error) { - setLoader(false); - } - }; - - const removeTabListItem = async (e, i) => { - e.preventDefault(); - setEditable(false); - setLoader(true); - setFolderList([]); - let list = tabList.filter((itm, j) => { - if (j <= i) { - return itm; - } - }); - setTabList(list); - setIsAddField(false); - try { - let _len = list.length - 1; - let url = `${parseBaseUrl}classes/${props.schema.data.ClassName}?where={"${props.schema.data.ParentFolderField}":{"__type":"Pointer","className":"${props.schema.data.ClassName}","objectId":"${list[_len].objectId}"}}`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - await axios.get(url, { headers: headers }).then((result) => { - if (result) { - setFolderList(result.data.results); - setLoader(false); - } - setLoader(false); - }); - } catch (error) { - setLoader(false); - } - }; - - const onDeleteFolder = async (e) => { - e.preventDefault(); - if (folderList.length > 0) { - alert( - "Folder should not delete. To delete first delete sub items in it." - ); - } else if (window.confirm(`Are you sure you want to delete this record`)) { - try { - setLoader(true); - let len = tabList.length - 1; - - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - var deleted = Parse.Object.extend(props.schema.data.ClassName); - var query = new Parse.Query(deleted); - await query.get(tabList[len].objectId).then( - (del) => { - del.destroy().then( - (y) => { - if (y) { - setLoader(false); - let list = tabList.filter((itm, j) => { - if (j !== len) return itm; - }); - setTabList(list); - if (list.length > 0) { - let len = list.length - 1; - selectedItemList(list[len]); - } else { - selectFolderHandle(); - } - alert("Folder deleted successfully."); - } - }, - (error) => { - alert(error.message); - setLoader(false); - } - ); - }, - (error) => { - console.log("error ", error); - // The object was not retrieved successfully. - setLoader(false); - } - ); - } catch (error) { - setLoader(false); - console.log(error); - } - } - }; - - const onSubmitResult = async (e) => { - setIsShowModal(false); - e.preventDefault(); - //console.log("tabList ", tabList); - if (tabList.length > 0) { - try { - let len = tabList.length - 1; - setSelectedFolder({ - Topic: tabList[len][`${props.schema.data.FolderNameField}`], - description: tabList[len][`${props.schema.data.FolderDescription}`] - }); - props.onChange(tabList[len]["objectId"]); - let url = "Folders"; - tabList.forEach((t) => { - url = url + " / " + t[`${props.schema.data.FolderNameField}`]; - }); - setTabURL(url); - setIsAddField(false); - if (!props.formData) { - setTabList([]); - } - } catch (error) { - setIsAddField(false); - alert(error.message); - } - } else { - setIsAddField(false); - } - }; - - const editFolderDisplay = async (formData) => { - try { - let objectId = formData.objectId; - let className = formData.className; - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - const fldr = Parse.Object.extend(className); - let query = new Parse.Query(fldr); - query.equalTo("objectId", objectId); - const result = await query.first(); - let resultJson = result.toJSON(); - let CustomTabList = []; - if (resultJson) { - CustomTabList.push(resultJson); - if (resultJson[`${props.schema.data.ParentFolderField}`]) { - let tabsRes = resultJson[`${props.schema.data.ParentFolderField}`]; - let looping = false; - do { - let fldttr = Parse.Object.extend(tabsRes.className); - let query2 = new Parse.Query(fldttr); - query2.equalTo("objectId", tabsRes.objectId); - let custome_res = await query2.first(); - if (custome_res) { - let tabsData = custome_res.toJSON(); - CustomTabList.push(tabsData); - if (tabsData[`${props.schema.data.ParentFolderField}`]) { - tabsRes = tabsData[`${props.schema.data.ParentFolderField}`]; - looping = true; - } else { - looping = false; - } - } - } while (looping); - } - let url = "Folders"; - CustomTabList.length > 0 && - CustomTabList.reverse().forEach( - (t) => (url = url + " / " + t[props.schema.data.FolderNameField]) - ); - setTabURL(url); - setSelectedFolder({ - Topic: resultJson[`${props.schema.data.FolderNameField}`], - description: resultJson[`${props.schema.data.FolderDescription}`] - }); - setTabList(CustomTabList); - props.onChange(resultJson.objectId); - } - } catch (error) { - console.log(error); - } - }; - - const handleSubmit = async ({ formData }) => { - setLoader(true); - - try { - let RowData = formData; - let _scanData = schemaState; - Object.keys(_scanData).forEach(function (key) { - let _dd = _scanData[key]; - Object.keys(_dd).forEach(function (k) { - if (_dd[k].component === "AutoSuggest" && _dd[k].isPointer) { - let pointer = { - __type: "Pointer", - className: _dd[k].class, - objectId: RowData[k] - }; - RowData[k] = pointer; - } - if (_dd[k].format === "date") { - let newdate = new Date(RowData[k]); - RowData[k] = newdate; - } - if (_dd[k].component === "DateTime") { - let newDate11; - if (!RowData[k]) { - newDate11 = new Date(); - } else { - newDate11 = new Date(RowData[k]); - } - RowData[k] = newDate11; - } - if (_dd[k].component === "CurrencyInput") { - if (_dd[k].currencyColumn) { - RowData[`${_dd[k].currencyColumn}`] = _dd[k].defaultcurrency; - } - } - if (_dd[k].data !== undefined) { - if (_dd[k].data.isPointer) { - let pointer = {}; - if (RowData[k] && RowData[k] !== "Select") { - if (_dd[k].data.class) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: _dd[k].data.class, - objectId: RowData[k] - }; - } - } else { - pointer = { - __type: "Pointer", - className: localStorage.getItem("extended_class"), - objectId: RowData[k] - }; - } - - RowData[k] = pointer; - } - } - if (_dd[k].data.FolderTypeValue) { - let obj = { - __type: "Pointer", - className: _dd[k].data.ClassName, - objectId: RowData[k] - }; - RowData[k] = obj; - } - } - if (_dd[k].type === "string") { - let d = RowData[k]; - if (typeof d === "string") { - RowData[k] = d.trim(); - } - } - }); - }); - - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - - var forms = Parse.Object.extend(className); - var folder = new forms(); - folder.set( - props.schema.data.FolderNameField, - formData[props.schema.data.FolderNameField] - ); - if (props.schema.data.FolderDescription) { - folder.set( - props.schema.data.FolderDescription, - formData[props.schema.data.FolderDescription] - ); - } - - folder.set("AppId", appId); - folder.set( - props.schema.data.FolderTypeField, - props.schema.data.FolderTypeValue - ); - const currentUser = Parse.User.current(); - folder.set("CreatedBy", Parse.User.createWithoutData(currentUser.id)); - if (tabList.length > 0) { - let len = tabList.length - 1; - folder.set(props.schema.data.ParentFolderField, { - __type: "Pointer", - className: props.schema.data.ClassName, - objectId: tabList[len]["objectId"] - }); - } - folder.save(RowData).then( - (result) => { - RowData = {}; - if (result) { - setIsAddField(false); - setLoader(false); - if (tabList.length > 0) { - let len = tabList.length - 1; - selectedItemList(tabList[len]); - } else { - selectFolderHandle(); - } - } - }, - (error) => { - console.log("error ", error); - setLoader(false); - } - ); - } catch (error) { - setLoader(false); - } - }; - - useEffect(() => { - if (props.formData) { - editFolderDisplay(props.formData); - } - - // eslint-disable-next-line - }, [props.formData]); - - useEffect(() => { - if (defaultState) { - selectFolderHandle(); - } - - // eslint-disable-next-line - }, [defaultState]); - const customStyles = { - content: { - top: "50%", - left: "50%", - right: "auto", - bottom: "auto", - marginRight: "-50%", - transform: "translate(-50%, -50%)", - backgroundColor: "white", - padding: 0 - }, - overlay: { - width: "100%", - backgroundColor: "rgba(0, 0, 0, 0.75)", - zIndex: 50 - } - }; - - return ( - <React.Fragment> - <LabelField - Title={props.schema.title} - Name={props.name} - Required={props.required} - HelpBody={props.schema.helpbody} - HelpLink={props.schema.helplink} - /> - <br /> - <div className="block max-w-sm bg-white border border-gray-200 shadow hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700"> - <div - style={{ - display: "flex", - color: "black", - fontWeight: "bold", - fontSize: "13px", - padding: "2%", - alignItems: "center" - }} - > - <div style={{ width: "20%" }}> - <div - className="pull-left" - title="Select Folder" - style={{ - color: "#33bbff", - margin: "auto", - padding: "10px 10px", - textAlign: "center" - }} - > - <i - className="far fa-folder-open" - style={{ fontSize: "40px" }} - aria-hidden="true" - ></i> - </div> - </div> - <div style={{ margin: "0px 10px 0 20px", width: "80%" }}> - <div> - {selectedFolder && selectedFolder.Topic - ? selectedFolder.Topic - : "Root"} - <i - className="fa fa-pencil" - title="Select Folder" - style={{ fontSize: 17, cursor: "pointer", marginLeft: 12 }} - onClick={selectFolderHandle} - ></i> - {selectedFolder && ( - <a - className="pull-right" - onClick={() => { - setSelectedFolder(undefined); - setTabURL(undefined); - props.onChange(undefined); - }} - > - <i - className="fa fa-times-circle-o" - aria-hidden="true" - style={{ fontSize: 17 }} - ></i> - </a> - )} - </div> - {TabURL && ( - <div - style={{ fontSize: "10px", color: "gray", fontWeight: "bold" }} - > - ({TabURL}) - </div> - )} - </div> - </div> - </div> - {/* save document in folder and add new folder modal */} - <Modal - isOpen={isShowModal} - onRequestClose={() => setIsShowModal(false)} - shouldCloseOnOverlayClick={false} - contentLabel="Modal" - style={customStyles} - > - <div className="w-full min-w-[300px] md:min-w-[500px]"> - {/* header */} - <div - style={{ - display: "flex", - justifyContent: "space-between", - alignItems: "center", - backgroundColor: "rgba(203, 200, 200, 0.09)" - }} - > - <div style={{ padding: "10px" }}> - <h4 className=" text-black">Select Folder</h4> - </div> - <div style={{ padding: "10px" }}> - <button - className="btn btn-sm pull-right" - data-dismiss="modal" - title="Select Folder" - style={{ - width: "auto", - backgroundColor: "white", - border: "1px solid gray", - boxshadow: "rgba(100, 100, 111, 0.2) 0px 7px 29px 0px" - }} - onClick={(e) => { - e.preventDefault(); - setIsAddField(false); - setFolderList([]); - setEditable(false); - if (!props.formData) { - setTabList([]); - } - setIsShowModal(false); - }} - > - <span aria-hidden="true">×</span> - </button> - </div> - </div> - <hr /> - {/* body */} - <div className="p-3 space-y-6"> - <div - style={{ - color: "#ac4848", - cursor: "pointer", - fontSize: "14px", - fontWeight: "500" - }} - > - <a - onClick={() => { - setTabList([]); - setIsAddField(false); - setDefaultState(true); - setEditable(false); - }} - > - Folders - </a> - {" / "} - - {tabList && - tabList.map((tab, i) => ( - <React.Fragment key={`${tab.objectId}-${i}`}> - <a - title={tab[`${props.schema.data.FolderNameField}`]} - onClick={(e) => removeTabListItem(e, i)} - > - {tab[`${props.schema.data.FolderNameField}`]} - </a> - {" / "} - </React.Fragment> - ))} - <hr /> - </div> - {/* {editable && ( - <TreeEditForm - FormId={props.schema.data.FormId} - objectId={editId} - HideView={(cl) => { - setEditable(cl); - selectFolderHandle(); - }} - /> - )} */} - {isAddField && !loader && !editable && ( - <TreeFormComponent - Id={props.schema.data.FormId} - handleSubmit={handleSubmit} - ParentField={props.schema.parent && props.schema.parent} - ParentValue={props.schema.parent && props.parent} - ChildField={props.child && props.child} - ClassName={(cls) => setClassName(cls)} - SchemaState={(cls) => setSchemaState(cls)} - /> - )} - {loader && ( - <div - className="loader-01" - style={{ - marginTop: "50px", - marginLeft: "50%", - color: "rgb(0,28,28)", - fontSize: "35px" - }} - ></div> - )} - - {!isAddField && !editable && ( - <div - style={{ - maxHeight: "280px", - overflowY: "auto", - marginTop: "5px" - }} - > - <ul> - {folderList && - folderList.map( - (fldr) => - fldr[props.schema.data.FolderTypeField] === - props.schema.data.FolderTypeValue && ( - <li - key={`${fldr.objectId}`} - style={{ - listStyle: "none", - padding: "10px 20px", - textTransform: "capitalize", - fontWeight: 300, - border: "1px solid gray", - borderRadius: "1px", - marginTop: "8px", - transition: "all 0.75s ease", - WebkitTransition: "all 0.5s ease", - MozTransition: "all 0.5s ease", - MsTransition: "all 0.5s ease", - OTransition: "all 0.5 ease", - display: "flex", - alignItems: "center", - justifyContent: "space-between" - }} - > - <div - style={{ - display: "flex", - alignItems: "center" - }} - > - <i - className={"fa fa-folder"} - style={{ - fontSize: "1.4rem", - color: "skyblue" - }} - aria-hidden="true" - ></i> - <a - style={{ - fontWeight: "bold", - fontSize: "12px", - marginLeft: "4px", - cursor: "pointer" - }} - onClick={() => { - setTabList((tabs) => tabs.concat(fldr)); - selectedItemList(fldr); - }} - > - {fldr[`${props.schema.data.FolderNameField}`]} - </a> - </div> - - {/* {fldr[props.schema.data.FolderTypeField] === - props.schema.data.FolderTypeValue && ( - <a - className="float-right" - onClick={() => { - setEditable(true); - setEditId(fldr.objectId); - }} - > - <i - className={"fa fa-pencil"} - title={"Edit Folder"} - style={{ - fontSize: "0.9rem", - color: "purple", - cursor: "pointer" - }} - aria-hidden="true" - ></i> - </a> - )} */} - </li> - ) - )} - </ul> - </div> - )} - </div> - {/* footer */} - - <div className="flex items-center p-3 space-x-2 border-t border-gray-200 rounded-b dark:border-gray-600 justify-between"> - <button - className="btn btn-sm float-left createFolder" - title="Create New Folder" - onClick={(e) => { - e.preventDefault(); - setIsAddField(true); - }} - > - {" "} - <i - className="fa fa-plus" - style={{ fontSize: "1.5rem" }} - aria-hidden="true" - ></i> - </button> - {!isAddField && !editable && ( - <div className="flex"> - {tabList.length > 0 && ( - <button - className="btn btn-sm float-right deleteFolder" - title="Delete Folder" - onClick={onDeleteFolder} - > - {" "} - <i - className="fa fa-trash" - style={{ fontSize: "1rem" }} - aria-hidden="true" - ></i> - </button> - )} - <button - className="btn btn-sm float-right saveFolder" - title="Save Here" - onClick={onSubmitResult} - > - {" "} - {/* <i - className="fa fa-floppy-o" - style={{ fontSize: "2rem" }} - aria-hidden="true" - ></i> */} - <i - className="fas fa-save" - aria-hidden="true" - style={{ fontSize: "20px" }} - ></i> - </button> - </div> - )} - </div> - </div> - </Modal> - </React.Fragment> - ); -}; - -const mapStateToProps = (state) => { - return { - parent: state.Level1_Dropdown, - child: state.Level2_Dropdown - }; -}; - -export default connect(mapStateToProps)(TreeWidget); diff --git a/apps/OpenSign/src/components/fields/FileUpload.js b/apps/OpenSign/src/components/fields/FileUpload.js deleted file mode 100644 index e6c632a02..000000000 --- a/apps/OpenSign/src/components/fields/FileUpload.js +++ /dev/null @@ -1,312 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { SaveFileSize } from "../../constant/saveFileSize"; -import Parse from "parse"; -import sanitizeFileName from "../../primitives/sanitizeFileName"; -import DropboxChooser from "./DropboxChoose"; -const FileUpload = (props) => { - const [parseBaseUrl] = useState(localStorage.getItem("baseUrl")); - const [parseAppId] = useState(localStorage.getItem("parseAppId")); - const [_fileupload, setFileUpload] = useState(""); - const [fileload, setfileload] = useState(false); - const [Message] = useState(false); - const [percentage, setpercentage] = useState(0); - - const REQUIRED_FIELD_SYMBOL = "*"; - - useEffect(() => { - if (!props.formData) { - setFileUpload([]); - props.onChange(undefined); - } - // eslint-disable-next-line - }, [props.formData]); - const onChange = (e) => { - try { - let files = e.target.files; - if (typeof files[0] !== "undefined") { - if (props.schema.filetypes && props.schema.filetypes.length > 0) { - var fileName = files[0].name; - var fileNameExt = fileName - .substr(fileName.lastIndexOf(".") + 1) - .toLowerCase(); - let Extensions = props.schema.filetypes.map((x) => x.toLowerCase()); - let arr = Extensions.filter((x) => x === fileNameExt); - if (arr.length > 0) { - console.log("multiple type"); - } else { - alert( - "Only these file types are accepted : " + Extensions.join(", ") - ); - } - } - if (props.schema.maxfilesizeKB && props.schema.maxfilesizeKB !== "") { - // console.log(Math.round(files[0].size / 1024)); - if ( - Math.round(Number(files[0].size) / 1024) >= - props.schema.maxfilesizeKB - ) { - alert( - `The selected file size is too large. Please select a file less than ${Math.round( - props.schema.maxfilesizeKB / 1024 - )} MB` - ); - return; - } - } - handleFileUpload(files[0]); - } else { - alert("Please select file."); - return false; - } - } catch (error) { - alert(error.message); - return false; - } - }; - - const handleFileUpload = async (file) => { - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - setfileload(true); - const size = file.size; - const fileName = file.name; - const name = sanitizeFileName(fileName); - const pdfFile = file; - const parseFile = new Parse.File(name, pdfFile); - - try { - const response = await parseFile.save({ - progress: (progressValue, loaded, total, { type }) => { - if (type === "upload" && progressValue !== null) { - const percentCompleted = Math.round((loaded * 100) / total); - // console.log("percentCompleted ", percentCompleted); - setpercentage(percentCompleted); - } - } - }); - - setFileUpload(response.url()); - props.onChange(response.url()); - setfileload(false); - // The response object will contain information about the uploaded file - // console.log("File uploaded:", response); - - // You can access the URL of the uploaded file using response.url() - // console.log("File URL:", response.url()); - if (response.url()) { - SaveFileSize(size, response.url()); - return response.url(); - } - } catch (error) { - setfileload(false); - setpercentage(0); - console.error("Error uploading file:", error); - } - }; - - const dropboxSuccess = async (files) => { - // console.log("file ", files); - setfileload(true); - const file = files[0]; - const url = file.link; - const size = file.bytes; - const mb = Math.round(file.bytes / Math.pow(1024, 2)); - - if (mb > 10) { - setTimeout(() => { - alert( - `The selected file size is too large. Please select a file less than 10 MB` - ); - }, 500); - return; - } else { - const name = sanitizeFileName(file.name); - - const parseFile = new Parse.File(name, { uri: url }); - - try { - const response = await parseFile.save({ - progress: (progressValue, loaded, total, { type }) => { - if (type === "upload" && progressValue !== null) { - const percentCompleted = Math.round((loaded * 100) / total); - // console.log("percentCompleted ", percentCompleted); - setpercentage(percentCompleted); - } - } - }); - // console.log("response.url() ", response.url()); - setFileUpload(response.url()); - props.onChange(response.url()); - setfileload(false); - - if (response.url()) { - SaveFileSize(size, response.url()); - return response.url(); - } - } catch (error) { - setfileload(false); - setpercentage(0); - console.error("Error uploading file:", error); - } - } - }; - const dropboxCancel = async () => { - console.log("cancel clicked "); - }; - let fileView = - props.formData && - props.schema.uploadtype === "s3viajw" ? null : props.formData && - props.formData ? ( - <React.Fragment> - <a - href={props.formData} - title={props.formData} - style={{ paddingBottom: "10px", color: "blue" }} - > - Download - </a> - </React.Fragment> - ) : fileload === false ? null : ( - <React.Fragment> - <a - href={_fileupload} - title={_fileupload} - style={{ paddingBottom: "10px" }} - > - Download - </a> - <br /> - </React.Fragment> - ); - - return ( - <React.Fragment> - <div style={{ display: "inline-block" }}> - <label htmlFor={props.name}> - {props.schema.title} - {props.required && ( - <span className="required">{REQUIRED_FIELD_SYMBOL}</span> - )} - {fileload ? ( - <div className="flex items-center gap-x-2"> - <div className="h-2 rounded-full w-[200px] md:w-[400px] bg-gray-200"> - <div - className="h-2 rounded-full bg-blue-500" - style={{ width: `${percentage}%` }} - ></div> - </div> - <span className="text-black text-sm">{percentage}%</span> - </div> - ) : ( - Message && ( - <span style={{ fontSize: "9px", marginLeft: "4px" }}> - Processing will take 5-10 mins.... - </span> - ) - )} - {props.schema.helpbody ? ( - <div className="dropdown pull-right"> - <i - className="far fa-question-circle dropdown-toggle hovereffect" - aria-hidden="true" - id="dropdownMenuButton" - data-toggle="dropdown" - aria-haspopup="true" - aria-expanded="false" - style={{ - fontSize: "12px", - color: "purple", - cursor: "pointer !important", - position: "relative", - bottom: "0px", - left: "0px", - paddingBottom: "4px", - paddingLeft: "4px" - }} - ></i> - <div - className="dropdown-menu" - aria-labelledby="dropdownMenuButton" - style={{ - marginleft: "-121px", - margintop: "-14px", - position: "absolute", - padding: "10px", - top: "102px!important" - }} - > - <br /> - {props.schema.helplink ? ( - <a - href={props.schema.helplink} - target="_blank" - rel="noreferrer" - className="btn btn-xs btn-primary" - > - Read more.. - </a> - ) : null} - </div> - </div> - ) : null} - <span style={{ marginLeft: "10px" }}>{fileView}</span> - </label> - </div> - - <> - {props.formData ? ( - <div className="flex gap-2 justify-center items-center"> - <div className="flex justify-between items-center px-2 py-[3px] w-full font-bold rounded border-[1px] border-[#ccc] text-gray-500 bg-white text-[13px]"> - <div className="break-all"> - file selected : {props.formData?.split("/")[3]?.split("_")[1]} - </div> - <div - onClick={() => { - console.log("clicked"); - setFileUpload([]); - props.onChange(undefined); - }} - className="cursor-pointer px-[10px] text-[20px] font-bold bg-white text-red-500" - > - <i className="fa-solid fa-xmark"></i> - </div> - </div> - {process.env.REACT_APP_DROPBOX_API_KEY && ( - <DropboxChooser - onSuccess={dropboxSuccess} - onCancel={dropboxCancel} - /> - )} - </div> - ) : ( - <div className="flex gap-2 justify-center items-center"> - <input - type="file" - id="hashfile" - style={{ - border: "1px solid #ccc", - color: "gray", - backgroundColor: "white", - padding: "5px 10px", - borderRadius: "4px", - fontSize: "13px", - width: "100%", - fontWeight: "bold" - }} - accept="application/pdf,application/vnd.ms-excel" - onChange={onChange} - /> - {process.env.REACT_APP_DROPBOX_API_KEY && ( - <DropboxChooser - onSuccess={dropboxSuccess} - onCancel={dropboxCancel} - /> - )} - </div> - )} - </> - </React.Fragment> - ); -}; - -export default FileUpload; diff --git a/apps/OpenSign/src/components/fields/HiddenField.js b/apps/OpenSign/src/components/fields/HiddenField.js deleted file mode 100644 index 09d582ed4..000000000 --- a/apps/OpenSign/src/components/fields/HiddenField.js +++ /dev/null @@ -1,98 +0,0 @@ -import React, { Component } from "react"; -import Parse from "parse"; -// import axios from "axios"; - -export class HiddenField extends Component { - state = { - baseUrl: localStorage.getItem("baseUrl"), - parseAppId: localStorage.getItem("parseAppId"), - _fields: "" - }; - loadData = async () => { - if (this.props.schema.default) { - this.setState({ _fields: this.props.schema.default }); - } else { - try { - Parse.serverURL = this.state.baseUrl; - Parse.initialize(this.state.parseAppId); - let currentUser = await Parse.User.current(); - if (localStorage.getItem("Extand_Class")) { - let _rdata = JSON.parse(localStorage.getItem("Extand_Class")); - let custome_Filed = ""; - let splitArray = this.props.schema.data.valueKey.split("."); - if (splitArray.length > 1) { - custome_Filed = _rdata[0][splitArray[0]][splitArray[1]]; - } else { - let _Filed = _rdata[0][splitArray[0]]; - if (typeof _Filed === "object") { - custome_Filed = { - __type: "Pointer", - className: _Filed["className"], - objectId: _Filed["objectId"] - }; - } else { - custome_Filed = _rdata[0][splitArray[0]]; - } - } - this.setState({ _fields: custome_Filed }); - } else { - if (currentUser) { - // let url = `${this.state.baseUrl}classes/${localStorage.getItem( - // "extended_class" - // )}?where={"UserId":{"__type":"Pointer","className":"_User","objectId":"${ - // currentUser.id - // }"}}&keys=${this.props.schema.data.valueKey}`; - // const headers = { - // "Content-Type": "application/json", - // "X-Parse-Application-Id": this.state.parseAppId - // }; - // await axios.get(url, { headers: headers }).then((res) => { - // let custome_Filed = ""; - // let _rdata = res.data.results; - // let splitArray = this.props.schema.data.valueKey.split("."); - // if (splitArray.length > 1) { - // custome_Filed = _rdata[0][splitArray[0]][splitArray[1]]; - // } else { - // console.log(_rdata[0][splitArray[0]]); - // custome_Filed = _rdata[0][splitArray[0]]; - // } - // this.setState({ _fields: custome_Filed }); - // }); - - const res = await Parse.Cloud.run("getUserDetails", { - email: currentUser.get("email") - }); - let custome_Filed = ""; - const result = res.toJSON(); - let _rdata = [result]; - let splitArray = this.props.schema.data.valueKey.split("."); - if (splitArray.length > 1) { - custome_Filed = _rdata[0][splitArray[0]][splitArray[1]]; - } else { - console.log(_rdata[0][splitArray[0]]); - custome_Filed = _rdata[0][splitArray[0]]; - } - this.setState({ _fields: custome_Filed }); - } - } - } catch (error) { - console.log("err", error); - } - } - }; - componentDidMount() { - this.loadData(); - } - - render() { - return ( - <input - type="hidden" - value={this.state._fields} - onChange={this.props.onChange(this.state._fields)} - /> - ); - } -} - -export default HiddenField; diff --git a/apps/OpenSign/src/components/fields/LabelField.js b/apps/OpenSign/src/components/fields/LabelField.js deleted file mode 100644 index dfa71f3cc..000000000 --- a/apps/OpenSign/src/components/fields/LabelField.js +++ /dev/null @@ -1,70 +0,0 @@ -import React from "react"; -import parse from "html-react-parser"; -import PropTypes from "prop-types"; - -const LabelField = (props) => { - const { Title, Name, Required, HelpBody, HelpLink } = props; - const REQUIRED_FIELD_SYMBOL = "*"; - return ( - <div style={{ display: "inline-block" }}> - <label htmlFor={Name}> - {Title} - {Required && <span className="required">{REQUIRED_FIELD_SYMBOL}</span>} - {HelpBody ? ( - <div className="dropdown pull-right"> - <i - className="far fa-question-circle dropdown-toggle hovereffect pull-right" - aria-hidden="true" - id="dropdownMenuButton" - data-toggle="dropdown" - aria-haspopup="true" - aria-expanded="false" - style={{ - fontSize: "12px", - color: "purple", - cursor: "pointer !important", - position: "relative", - bottom: "0px", - left: "0px", - paddingBottom: "4px", - paddingLeft: "4px" - }} - ></i> - <div - className="dropdown-menu" - aria-labelledby="dropdownMenuButton" - style={{ - marginleft: "-121px", - margintop: "-14px", - position: "absolute", - padding: "10px", - top: "102px!important" - }} - > - {parse(` - ${HelpBody} - `)} - <br /> - {HelpLink ? ( - <a - href={HelpLink} - target="_blank" - rel="noreferrer" - className="btn btn-xs btn-primary" - > - Read more.. - </a> - ) : null} - </div> - </div> - ) : null} - </label> - </div> - ); -}; - -LabelField.propTypes = { - Name: PropTypes.string.isRequired, - Title: PropTypes.string.isRequired -}; -export default LabelField; diff --git a/apps/OpenSign/src/components/fields/Level1Dropdown.js b/apps/OpenSign/src/components/fields/Level1Dropdown.js deleted file mode 100644 index 42228a6f6..000000000 --- a/apps/OpenSign/src/components/fields/Level1Dropdown.js +++ /dev/null @@ -1,482 +0,0 @@ -import React, { useEffect, useState } from "react"; -import { connect } from "react-redux"; -import { onChangeLevel1Dropdown } from "../../redux/actions/index"; -import axios from "axios"; -import Parse from "parse"; -import parse from "html-react-parser"; - -const Level1Dropdown = (props) => { - const [parseBaseUrl] = useState(localStorage.getItem("baseUrl")); - const [parseAppId] = useState(localStorage.getItem("parseAppId")); - const [Level1_DD, setLevel1_DD] = useState([]); - const [toastColor] = useState("#d9534f"); - const [toastDescription, setToastDescription] = useState(""); - const [active, setActive] = useState(false); - - const getParams = (offset) => { - const params = { - skip: offset - }; - return params; - }; - - const Level1DropdownData = async () => { - try { - if ( - props.formData && - props.uiSchema["ui:disabled"] && - props.formData !== "Select" - ) { - let url = `${parseBaseUrl}classes/${props.schema.data.class}/${props.formData}`; - if (typeof props.formData === "object") { - url = `${parseBaseUrl}classes/${props.schema.data.class}/${props.formData.objectId}`; - } - let headers1 = { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - let data = []; - let response = []; - await axios.get(url, { headers: headers1 }).then((res) => { - if (res) { - data.push(res.data); - } - }); - - if (data.length > 0) { - let temp = []; - data.forEach((x) => { - let opt = ""; - if (Array.isArray(x[props.schema.data.valueKey])) { - x[props.schema.data.valueKey].forEach((tt) => { - if (typeof tt === "object") { - opt = { - objectId: tt[props.schema.data.displayKey], - option: tt[props.schema.data.displayKey] - }; - } else { - opt = { - objectId: tt, - option: tt - }; - } - temp.push(opt); - }); - } else if (props.schema.data.isPointer) { - if (props.schema.data.valueKey.includes(".")) { - let newArr = props.schema.data.valueKey.split("."); - if (newArr.length === 2) { - opt = { - objectId: x[newArr[0]][newArr[1]], - option: x[props.schema.data.displayKey] - }; - } else { - opt = { - objectId: x[newArr[0]], - option: x[props.schema.data.displayKey] - }; - } - } else { - opt = { - objectId: x[props.schema.data.valueKey], - option: x[props.schema.data.displayKey] - }; - } - temp.push(opt); - } else { - opt = { - objectId: x[props.schema.data.valueKey], - option: x[props.schema.data.displayKey] - }; - temp.push(opt); - } - }); - response = temp; - setLevel1_DD(response); - setActive(false); - if (response.length === 1) { - props.onChangeLevel1Dropdown(response[0].objectId, props.name); - props.onChange(response[0].objectId); - } else if (response.length === 0) { - props.onChangeLevel1Dropdown("", props.name); - props.onChange(""); - } - } - } else { - let response = []; - setActive(true); - Parse.serverURL = parseBaseUrl; - Parse.initialize(parseAppId); - const currentUser = Parse.User.current(); - - // eslint-disable-next-line - var reg = /(\#.*?\#)/gi; - let str = props.schema.data.query; - var test; - if (str.includes("#")) { - let res; - if (localStorage.getItem("Extand_Class")) { - let data = JSON.parse(localStorage.getItem("Extand_Class")); - res = data[0]; - } else { - const currentUser = Parse.User.current(); - res = await Parse.Cloud.run("getUserDetails", { - email: currentUser.get("email") - }); - if (res) res = res.toJSON(); - } - - if (res) { - let json = res; - let output = str.match(reg); - if (output.length === 1) { - output = output.join(); - output = output.substring(1, output.length - 1); - output = output.split("."); - if (output.length === 1) { - let out = output[0]; - if (json[out]) { - if (typeof json[out] === "object") { - test = str.replace(reg, JSON.stringify(json[out])); - } else { - test = str.replace(reg, json[out]); - } - } else { - test = str.replace(reg, currentUser.id); - } - } else if (output.length === 2) { - let out1 = json[output[0]][output[1]]; - if (out1) { - test = str.replace(reg, out1); - } - } - } else if (output.length === 2) { - let output1 = output[0]; - output1 = output1.substring(1, output1.length - 1); - output1 = output1.split("."); - if (output1.length === 1) { - let out = output1[0]; - if (json[out]) { - if (typeof json[out] === "object") { - str = str.replace(output[0], JSON.stringify(json[out])); - } else { - str = str.replace(output[0], json[out]); - } - } else { - str = str.replace(output[0], currentUser.id); - } - } else if (output1.length === 2) { - let out1 = json[output1[0]][output1[1]]; - if (out1) { - str = str.replace(output[0], out1); - } - } - let output2 = output[1]; - output2 = output2.substring(1, output2.length - 1); - output2 = output2.split("."); - if (output2.length === 1) { - let out = output2[0]; - if (json[out]) { - if (typeof json[out] === "object") { - str = str.replace(output[1], JSON.stringify(json[out])); - } else { - str = str.replace(output[1], json[out]); - } - } else { - str = str.replace(output[1], currentUser.id); - } - } else if (output2.length === 2) { - let out1 = json[output2[0]][output2[1]]; - if (out1) { - str = str.replace(output[1], out1); - } - } - test = str; - } - } else { - setToastDescription( - `User not found in ${localStorage.getItem("extended_class")}` - ); - setActive(false); - var x = document.getElementById("Level_1"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 5000); - return; - } - } else { - test = str; - } - let url = `${parseBaseUrl}classes/${props.schema.data.class}?${test}`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - let fetchCount = 0; - let offset = 0; - let data = []; - /* eslint-disable no-constant-condition */ - while (true) { - const params = getParams(offset); - await axios - .get(url, { params: params, headers: headers }) - .then((response) => { - fetchCount = response.data.results.length; - offset += response.data.results.length; - - if (fetchCount > 0) { - response.data.results.forEach((x) => { - data.push(x); - }); - } - }) - .catch((err) => { - console.error("Problem", err.response); - setToastDescription(err.response.data.message); - setActive(false); - var x = document.getElementById("Level_1"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 5000); - }); - if (fetchCount === 0 || fetchCount < 100) { - break; - } - } - if (data.length > 0) { - let temp = []; - data.forEach((x) => { - let opt = ""; - if (Array.isArray(x[props.schema.data.valueKey])) { - x[props.schema.data.valueKey].forEach((tt) => { - if (typeof tt === "object") { - if (props.schema.data.isPointer) { - opt = { - objectId: tt["objectId"], - option: tt[props.schema.data.displayKey] - }; - } else { - opt = { - objectId: tt[props.schema.data.displayKey], - option: tt[props.schema.data.displayKey] - }; - } - } else { - opt = { - objectId: tt, - option: tt - }; - } - temp.push(opt); - }); - } else if (props.schema.data.isPointer) { - if (props.schema.data.valueKey.includes(".")) { - let newArr = props.schema.data.valueKey.split("."); - if (newArr.length === 2) { - let _dis = props.schema.data.displayKey.split("."); - if (_dis.length === 2) { - opt = { - objectId: x[newArr[0]][newArr[1]], - option: x[_dis[0]][_dis[1]] - }; - } else { - opt = { - objectId: x[newArr[0]][newArr[1]], - option: x[props.schema.data.displayKey] - }; - } - } else { - opt = { - objectId: x[newArr[0]], - option: x[props.schema.data.displayKey] - }; - } - } else { - opt = { - objectId: x[props.schema.data.valueKey], - option: x[props.schema.data.displayKey] - }; - } - temp.push(opt); - } else { - opt = { - objectId: x[props.schema.data.valueKey], - option: x[props.schema.data.displayKey] - }; - temp.push(opt); - } - }); - response = temp; - setLevel1_DD(response); - setActive(false); - if (!props.formData) { - props.onChangeLevel1Dropdown("", props.name); - } - if (response.length === 1) { - props.onChangeLevel1Dropdown(response[0].objectId, props.name); - props.onChange(response[0].objectId); - } else if (response.length === 0) { - props.onChangeLevel1Dropdown("", props.name); - props.onChange(""); - } - } else { - setActive(false); - } - } - } catch (e) { - try { - setToastDescription(e.message); - setActive(false); - x = document.getElementById("Level_1"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 5000); - } catch (error) { - console.log("Err", error); - } - } - }; - - useEffect(() => { - Level1DropdownData(); - // eslint-disable-next-line - }, []); - - useEffect(() => { - if (props.formData && props.formData[`objectId`]) { - props.onChangeLevel1Dropdown(props.formData.objectId, props.name); - } else if (props.formData) { - props.onChangeLevel1Dropdown(props.formData, props.name); - } - - // eslint-disable-next-line - }, [props.formData]); - - const selectDefault = () => { - props.onChange(Level1_DD[0].objectId); - props.onChangeLevel1Dropdown(Level1_DD[0].objectId, props.name); - }; - - const REQUIRED_FIELD_SYMBOL = "*"; - return ( - <React.Fragment> - <div style={{ display: "inline-block" }}> - <label htmlFor={props.name}> - {props.schema.title} - {props.required && ( - <span className="required">{REQUIRED_FIELD_SYMBOL}</span> - )} - {props.schema.data.helpbody ? ( - <div className="dropdown pull-right"> - <i - className="far fa-question-circle dropdown-toggle hovereffect pull-right" - aria-hidden="true" - id="dropdownMenuButton" - data-toggle="dropdown" - aria-haspopup="true" - aria-expanded="false" - style={{ - fontSize: "12px", - color: "purple", - cursor: "pointer !important", - position: "relative", - bottom: "0px", - left: "0px", - paddingBottom: "4px", - paddingLeft: "4px" - }} - ></i> - <div - className="dropdown-menu" - aria-labelledby="dropdownMenuButton" - style={{ - marginleft: "-121px", - margintop: "-14px", - position: "absolute", - padding: "10px", - top: "102px!important" - }} - > - {parse(` - ${props.schema.data.helpbody} - `)} - <br /> - {props.schema.data.helplink ? ( - <a - href={props.schema.data.helplink} - target="_blank" - rel="noreferrer" - className="btn btn-xs btn-primary" - > - Read more.. - </a> - ) : null} - </div> - </div> - ) : null} - </label> - </div> - - {Level1_DD && ( - <select - className="form-control" - name={props.name} - value={props.value} - required={props.required} - disabled={props.uiSchema["ui:disabled"]} - onChange={(e) => { - if (!e.target.value) { - if (props.schema.data.isPointer) { - localStorage.setItem("Level1", undefined); - props.onChangeLevel1Dropdown(undefined, props.name); - return props.onChange(undefined); - } else { - localStorage.setItem("Level1", e.target.value); - props.onChangeLevel1Dropdown(e.target.value, props.name); - return props.onChange(e.target.value); - } - } else { - localStorage.setItem("Level1", e.target.value); - props.onChangeLevel1Dropdown(e.target.value, props.name); - return props.onChange(e.target.value); - } - }} - readOnly={props.uiSchema["ui:disabled"] ? true : false} - defaultValue={Level1_DD.length === 1 && selectDefault} - > - <option value="">{!active ? "Select" : "loading..."}</option> - {Level1_DD && - Level1_DD.map((x, i) => ( - <React.Fragment key={i}> - {props.formData && props.formData.objectId ? ( - props.formData.objectId === x.objectId ? ( - <option value={x.objectId} selected> - {x.option} - </option> - ) : ( - <option value={x.objectId}>{x.option}</option> - ) - ) : props.formData && props.formData === x.objectId ? ( - <option value={x.objectId} selected> - {x.option} - </option> - ) : ( - <option value={x.objectId}>{x.option}</option> - )} - </React.Fragment> - ))} - </select> - )} - <div id="Level_1" style={{ backgroundColor: toastColor }}> - {toastDescription} - </div> - </React.Fragment> - ); -}; - -export default connect(null, { onChangeLevel1Dropdown })(Level1Dropdown); diff --git a/apps/OpenSign/src/components/fields/MultiSelectField.js b/apps/OpenSign/src/components/fields/MultiSelectField.js deleted file mode 100644 index 520e9398f..000000000 --- a/apps/OpenSign/src/components/fields/MultiSelectField.js +++ /dev/null @@ -1,709 +0,0 @@ -import React, { useState, useEffect } from "react"; -import { connect } from "react-redux"; -import Select from "react-select"; -import axios from "axios"; -import LabelField from "./LabelField"; -import ReactDragListView from "react-drag-listview"; -import AppendFormInForm from "../AppendFormInForm"; -import Modal from "react-modal"; -function arrayMove(array, from, to) { - array = array.slice(); - array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]); - return array; -} - -/** - * react-sortable-hoc is depcreated not usable from react 18.x.x - * need to replace it with @dnd-kit - * code changes required - */ - -const MultiSelectField = (props) => { - Modal.setAppElement("body"); - const [parseBaseUrl] = useState(localStorage.getItem("baseUrl")); - const [parseAppId] = useState(localStorage.getItem("parseAppId")); - const [state, setState] = useState(undefined); - // const [editFormData, setEditFormData] = useState([]); - const [selected, setSelected] = React.useState([]); - const [isModal, setIsModel] = useState(false); - const onChange = (selectedOptions) => setSelected(selectedOptions); - const [modalIsOpen, setModalIsOpen] = useState(false); - - const onSortEnd = ({ oldIndex, newIndex }) => { - const newValue = arrayMove(selected, oldIndex, newIndex); - setSelected(newValue); - }; - // console.log("props",props) - const GetSelectListData = async () => { - try { - let response = []; - let str = props.schema.data.query; - let _query; - /* eslint-disable no-useless-escape */ - let reg = /(\#.*?\#)/gi; - let extclass = - localStorage.getItem("Extand_Class") && - JSON.parse(localStorage.getItem("Extand_Class")); - let extRow = extclass.length && extclass[0]; - if (str.includes("#")) { - let output = str.match(reg); - output = output.join(); - output = output.substring(1, output.length - 1); - output = output.split("."); - - if (output.length === 2) { - let out1 = extRow[output[0]][output[1]]; - _query = str.replace(reg, out1 && out1); - } else { - let out1 = extRow[output[0]]; - _query = str.replace(reg, out1 && out1); - } - } else { - _query = str; - } - let url = `${parseBaseUrl}classes/${props.schema.data.class}?${_query}`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - await axios.get(url, { headers: headers }).then((res) => { - let temp = []; - let formArray = []; - let _selected = []; - if (props.schema.uiLayout === "MultiDropdownList") { - if (props.formData) { - props.formData.forEach((x) => { - if (typeof x === "object") { - formArray.push(x.objectId); - } else { - formArray.push(x); - } - }); - } - res.data.results.forEach((x) => { - let obj = {}; - if (formArray.includes(x[props.schema.data.valueKey])) { - obj = { - name: x[props.schema.data.displayKey], - value: x[props.schema.data.valueKey], - isChecked: true - }; - } else { - if (props.schema.selectAll) { - obj = { - name: x[props.schema.data.displayKey], - value: x[props.schema.data.valueKey], - isChecked: true - }; - } else { - obj = { - name: x[props.schema.data.displayKey], - value: x[props.schema.data.valueKey], - isChecked: false - }; - } - } - temp.push(obj); - }); - response = temp; - if (props.formData) { - let checkData = []; - response.forEach((x) => { - if (x.isChecked) { - checkData.push(x.value); - } - }); - setSelected(checkData); - } - setState({ [`${props.name}_DD`]: response }); - } else { - res.data.results.forEach((x) => { - let obj = {}; - if (props.formData) { - props.formData.forEach((x) => { - if (typeof x === "object") { - formArray.push(x.objectId); - } else { - formArray.push(x); - } - }); - } - - obj = { - label: x[props.schema.data.displayKey], - value: x[props.schema.data.valueKey] - }; - if (formArray.includes(x[props.schema.data.valueKey])) { - _selected.push(obj); - } - if (props.schema.selectAll) { - _selected.push(obj); - } - temp.push(obj); - }); - response = temp; - setState({ [`${props.name}_DD`]: response }); - setSelected(_selected); - } - }); - } catch (error) { - console.log("err", error); - } - }; - - const handleCheckChieldElement = (event) => { - let SelectLists = state[`${props.name}_DD`]; - let List = []; - SelectLists.forEach((select) => { - if (select.value === event.target.value) { - select.isChecked = event.target.checked; - } - if (select.isChecked) { - List.push(select.value); - } - }); - setSelected(List); - setState({ [`${props.name}_DD`]: SelectLists }); - }; - - // const Level1CheckList = async (id) => { - // try { - // let response = []; - // // eslint-disable-next-line - // let reg = /(\#.*?\#)/gi; - // let _query = props.schema.data.query; - // let output = _query.match(reg); - // if (output.length === 2) { - // let res; - // if (localStorage.getItem("Extand_Class")) { - // let data = JSON.parse(localStorage.getItem("Extand_Class")); - // res = data[0]; - // } - // output = output.filter((x) => x !== "#queryString#"); - // if (output.length === 1) { - // _query = _query.replace("#queryString#", id); - // output = output.join(); - // output = output.substring(1, output.length - 1); - // output = output.split("."); - // if (output.length > 0) { - // _query = _query.replace(reg, res[output[0]][output[1]]); - // } else { - // _query = _query.replace(reg, res[output[0]]); - // } - // } - // } else { - // _query = props.schema.data.query.replace(reg, id); - // } - - // let url = `${parseBaseUrl}classes/${props.schema.data.class}?${_query}`; - // const headers = { - // "Content-Type": "application/json", - // "X-Parse-Application-Id": parseAppId, - // "X-Parse-Session-Token": localStorage.getItem("accesstoken") - // }; - // await axios.get(url, { headers: headers }).then(async (res) => { - // let temp = []; - // let formArray = []; - // let _selected = []; - // if (editFormData.length > 0) { - // editFormData.forEach((x) => { - // if (typeof x === "object") { - // formArray.push(x.objectId); - // } else { - // formArray.push(x); - // } - // }); - // } else if ( - // props.schema.selectedData && - // Object.keys(props.schema.selectedData).length !== 0 && - // props.schema.selectedData.constructor === Object - // ) { - // try { - // let selectedDataQuery = props.schema.selectedData.query.replace( - // reg, - // id - // ); - // let selectedDataUrl = `${parseBaseUrl}classes/${props.schema.selectedData.class}?${selectedDataQuery}`; - - // await axios.get(selectedDataUrl, { headers }).then((sltres) => { - // let sltData = sltres.data.results; - // sltData.forEach((x) => { - // if (props.schema.selectedData.valueKey.includes(".")) { - // let sltArr = props.schema.selectedData.valueKey.split("."); - - // if (Array.isArray(x[sltArr[0]])) { - // x[sltArr[0]].forEach((l) => { - // formArray.push(l[sltArr[1]]); - // }); - // } else { - // formArray.push(x[sltArr[0][sltArr[1]]]); - // } - // } else { - // formArray.push(x[props.schema.selectedData.valueKey]); - // } - // }); - // }); - // } catch (error) {} - // } - // res.data.results.forEach((x) => { - // let obj = {}; - // if (props.schema.data.valueKey.includes(".")) { - // let newArr = props.schema.data.valueKey.split("."); - // if (Array.isArray(x[newArr[0]])) { - // if (props.schema.data.displayKey.includes(".")) { - // let _dis = props.schema.data.displayKey.split("."); - // x[newArr[0]].forEach((l) => { - // if (formArray.includes(l[newArr[1]])) { - // obj = { - // label: l[_dis[1]], - // value: l[newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // if (props.schema.selectAll) { - // obj = { - // label: l[_dis[1]], - // value: l[newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // obj = { - // label: l[_dis[1]], - // value: l[newArr[1]], - // isChecked: false - // }; - // } - // } - // temp.push(obj); - // }); - // } else { - // x[newArr[0]].forEach((l) => { - // if (formArray.includes(l[newArr[1]])) { - // obj = { - // label: x[props.schema.data.displayKey], - // value: l[newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // if (props.schema.selectAll) { - // obj = { - // label: x[props.schema.data.displayKey], - // value: l[newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // obj = { - // label: x[props.schema.data.displayKey], - // value: l[newArr[1]], - // isChecked: false - // }; - // } - // } - // temp.push(obj); - // }); - // } - // } else { - // if (props.schema.data.displayKey.includes(".")) { - // let disArr = props.schema.data.displayKey.split("."); - // if (formArray.includes(x[newArr[0]][newArr[1]])) { - // obj = { - // label: x[disArr[0]][disArr[1]], - // value: x[newArr[0]][newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // if (props.schema.selectAll) { - // obj = { - // label: x[disArr[0]][disArr[1]], - // value: x[newArr[0]][newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // obj = { - // label: x[disArr[0]][disArr[1]], - // value: x[newArr[0]][newArr[1]], - // isChecked: false - // }; - // } - // } - // } else { - // if (formArray.includes(x[newArr[0]][newArr[1]])) { - // obj = { - // label: x[props.schema.data.displayKey], - // value: x[newArr[0]][newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // if (props.schema.selectAll) { - // obj = { - // label: x[props.schema.data.displayKey], - // value: x[newArr[0]][newArr[1]], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // obj = { - // label: x[props.schema.data.displayKey], - // value: x[newArr[0]][newArr[1]], - // isChecked: false - // }; - // } - // } - // } - // } - // } else { - // if (Array.isArray(x[props.schema.data.valueKey])) { - // x[props.schema.data.valueKey].forEach((t) => { - // if (formArray.includes(t)) { - // obj = { - // label: t, - // value: t, - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // if (props.schema.selectAll) { - // obj = { - // label: t, - // value: t, - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // obj = { - // label: t, - // value: t, - // isChecked: false - // }; - // } - // } - // temp.push(obj); - // }); - // } else if (formArray.includes(x[props.schema.data.valueKey])) { - // obj = { - // label: x[props.schema.data.displayKey], - // value: x[props.schema.data.valueKey], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // if (props.schema.selectAll) { - // obj = { - // label: x[props.schema.data.displayKey], - // value: x[props.schema.data.valueKey], - // isChecked: true - // }; - // _selected.push(obj); - // } else { - // obj = { - // label: x[props.schema.data.displayKey], - // value: x[props.schema.data.valueKey], - // isChecked: false - // }; - // } - // } - // temp.push(obj); - // } - // }); - // response = temp; - // if (props.schema.uiLayout === "MultiDropdownList") { - // if (editFormData) { - // let checkData = []; - // response.forEach((x) => { - // if (x.isChecked) { - // checkData.push(x.value); - // } - // }); - // setSelected(checkData); - // } - // setState({ [`${props.name}_DD`]: response }); - // } else { - // setState({ [`${props.name}_DD`]: response }); - // setSelected(_selected); - // } - // }); - // } catch (error) {} - // }; - - const dragProps = { - onDragEnd(fromIndex, toIndex) { - const data = [...state[`${props.name}_DD`]]; - const item = data.splice(fromIndex, 1)[0]; - data.splice(toIndex, 0, item); - let NewList = []; - data.forEach((x) => { - if (x.isChecked) { - NewList.push(x.value); - } - }); - - setState({ [`${props.name}_DD`]: data }); - setSelected(NewList); - }, - nodeSelector: "li", - handleSelector: "a" - }; - - useEffect(() => { - if (!props.schema.parent) GetSelectListData(); - // eslint-disable-next-line - }, []); - - useEffect(() => { - if (props.schema.uiLayout === "MultiDropdownList") { - props.onChange(selected); - } else { - if (selected && selected.length) { - let newData = []; - selected.forEach((x) => { - newData.push(x.value); - }); - props.onChange(newData); - } - } - // eslint-disable-next-line - }, [selected]); - - // useState(() => { - // if (props.formData) { - // if (props.formData === "Select") { - // } else { - // setEditFormData(props.formData); - // } - // } - // // eslint-disable-next-line - // }, [props.formData]); - - const handleModalCloseClick = () => { - setIsModel(false); - setModalIsOpen(false); - }; - - const openModal = () => { - setModalIsOpen(true); - }; - - // `handleNewDetails` is used to set just save from quick form to selected option in dropdown - const handleNewDetails = (data) => { - setState({ [`${props.name}_DD`]: [...state[`${props.name}_DD`], data] }); - if (selected.length > 0) { - setSelected([...selected, data]); - } else { - setSelected([data]); - } - }; - if (props.schema.uiLayout === "MultiDropdownList") { - return ( - <React.Fragment> - <LabelField - Title={props.schema.title} - Name={props.name} - Required={props.required} - HelpBody={props.schema.helpbody} - HelpLink={props.schema.helplink} - /> - <ReactDragListView {...dragProps}> - <ul - style={{ - listStyleType: "square", - listStylePosition: "outside", - maxHeight: "250px", - overflow: "auto", - paddingTop: "10px", - paddingBottom: "10px", - border: "0px solid #b3b3b3", - borderRadius: "5px" - }} - > - {state && state[`${props.name}_DD`].length > 0 ? ( - state[`${props.name}_DD`].map((x, i) => { - return ( - <li key={i} className="multiSelectList"> - <input - key={x.value} - onClick={handleCheckChieldElement} - type="checkbox" - checked={x.isChecked} - style={{ marginTop: "7px" }} - value={x.value} - disabled={props.disabled} - />{" "} - <span style={{ marginTop: "7px" }}>{x.name}</span> - {props.schema.isSortable && !props.disabled && ( - <a - onClick={(e) => e.preventDefault()} - className="pull-right" - title="Sort List" - style={{ textDecoration: "none" }} - > - <i - className="fa fa-bars" - style={{ - fontSize: "30px", - color: "skyblue", - paddingTop: "11px" - }} - ></i> - </a> - )} - </li> - ); - }) - ) : ( - <li className="multiSelectList">No Record Found</li> - )} - </ul> - </ReactDragListView> - </React.Fragment> - ); - } - - return ( - <React.Fragment> - <LabelField - Title={props.schema.title} - Name={props.name} - Required={props.required} - HelpBody={props.schema.helpbody} - HelpLink={props.schema.helplink} - /> - <div style={{ display: "flex", gap: 5 }}> - <div style={{ flexWrap: "wrap", width: "100%" }}> - <Select - onSortEnd={onSortEnd} - distance={4} - isMulti - options={(state && state[`${props.name}_DD`]) || []} - value={selected} - onChange={onChange} - closeMenuOnSelect={false} - /> - </div> - - {props.schema.data.quickAddFormId && ( - <div - onClick={() => { - setIsModel(true); - openModal(); - }} - style={{ - cursor: "pointer", - borderRadius: 4, - border: "1px solid #ccc", - minHeight: 38, - minWidth: 48, - display: "flex", - justifyContent: "center", - alignItems: "center" - }} - > - <i className="fas fa-plus"></i> - </div> - )} - {/* {props.schema.data.quickAddFormId && ( - <div - className="modal fade" - id={"multiSelectModal" + props.schema.data.quickAddFormId} - tabIndex="-1" - role="dialog" - aria-labelledby="exampleModalLabel" - aria-hidden="true" - > - <div className="modal-dialog modal-lg" role="document"> - <div className="modal-content"> - <div className="modal-header"> - <button - type="button" - className="close" - data-dismiss="modal" - aria-label="Close" - onClick={handleModalCloseClick} - > - <i className="fa fa-times-circle" aria-hidden="true"></i> - </button> - </div> - <div className="modal-body"> - {isModal && ( - <AppendFormInForm - id={props.schema.data.quickAddFormId} - valueKey={props.schema.data.valueKey} - displayKey={props.schema.data.displayKey} - details={handleNewDetails} - closePopup={handleModalCloseClick} - /> - )} - </div> - </div> - </div> - </div> - )} */} - <Modal - isOpen={modalIsOpen} - onRequestClose={handleModalCloseClick} - shouldCloseOnOverlayClick={false} - contentLabel="Modal" - style={{ - content: { - top: "50%", - left: "50%", - right: "auto", - bottom: "auto", - transform: "translate(-50%, -50%)", - padding: 0 - }, - overlay: { - width: "100%", - backgroundColor: "rgba(0, 0, 0, 0.75)", - zIndex: 50 - } - }} - > - <div className="min-w-full md:min-w-[500px]"> - <div - type="button" - className="flex justify-between items-center p-3 border-b-[1px] border-gray-300" - > - <div className=" text-black text-xl font-semibold pl-3"> - Add Signer - </div> - <button onClick={handleModalCloseClick}> - <i - style={{ fontSize: 25 }} - className="fa fa-times-circle" - aria-hidden="true" - ></i> - </button> - </div> - - {isModal && ( - <AppendFormInForm - id={props.schema.data.quickAddFormId} - valueKey={props.schema.data.valueKey} - displayKey={props.schema.data.displayKey} - details={handleNewDetails} - closePopup={handleModalCloseClick} - /> - )} - </div> - </Modal> - </div> - </React.Fragment> - ); -}; - -const mapStateToProps = (state) => { - return { - Level1_Dropdown: state.Level1_Dropdown, - Level2_Dropdown: state.Level2_Dropdown, - Level3_Dropdown: state.Level3_Dropdown - }; -}; -export default connect(mapStateToProps, null)(MultiSelectField); diff --git a/apps/OpenSign/src/components/fields/Rjsf-layout.js b/apps/OpenSign/src/components/fields/Rjsf-layout.js deleted file mode 100644 index a48be8190..000000000 --- a/apps/OpenSign/src/components/fields/Rjsf-layout.js +++ /dev/null @@ -1,92 +0,0 @@ -import React from "react"; -import ObjectField from "@rjsf/core/lib/components/fields/ObjectField"; -import validator from "@rjsf/validator-ajv8"; -import { Col } from "react-bootstrap"; -import { retrieveSchema } from "@rjsf/utils"; - -class GridField extends ObjectField { - state = {}; - render() { - const { - uiSchema, - errorSchema, - idSchema, - - disabled, - readonly, - onBlur, - formData - } = this.props; - const { fields, rootSchema } = this.props.registry; - - const { SchemaField } = fields; - const schema = retrieveSchema(validator, this.props.schema, rootSchema); - const title = schema.title === undefined ? "" : schema.title; - const description = - schema && schema.description === undefined ? "" : schema.description; - // console.log('this.props.schema ', this.props.schema) - // console.log("schema ", schema); - const layout = uiSchema["ui:layout"]; - - return ( - <fieldset> - {title ? <h4>{title}</h4> : null} - {description ? <h6>{description}</h6> : null} - {layout.map((row, index) => { - return ( - <div className="row" key={index}> - {Object.keys(row).map((name, index) => { - const { doShow, ...rowProps } = row[name]; - let style = {}; - if (doShow && !doShow({ formData })) { - style = { display: "none" }; - } - if (schema.properties[name]) { - return ( - <Col {...rowProps} key={index} style={style}> - <SchemaField - name={name} - required={this.isRequired(name)} - schema={schema.properties[name]} - uiSchema={uiSchema[name]} - errorSchema={errorSchema[name]} - idSchema={idSchema[name]} - formData={formData[name]} - onChange={this.onPropertyChange(name)} - onBlur={onBlur} - registry={this.props.registry} - disabled={disabled} - readonly={readonly} - /> - </Col> - ); - } else { - const { render, ...rowProps } = row[name]; - let UIComponent = () => null; - - if (render) { - UIComponent = render; - } - - return ( - <Col {...rowProps} key={index} style={style}> - <UIComponent - name={name} - formData={formData} - errorSchema={errorSchema} - uiSchema={uiSchema} - schema={schema} - registry={this.props.registry} - /> - </Col> - ); - } - })} - </div> - ); - })} - </fieldset> - ); - } -} -export default GridField; diff --git a/apps/OpenSign/src/components/fields/SignersInput.js b/apps/OpenSign/src/components/fields/SignersInput.js index 0e9697965..af6016931 100644 --- a/apps/OpenSign/src/components/fields/SignersInput.js +++ b/apps/OpenSign/src/components/fields/SignersInput.js @@ -113,6 +113,7 @@ const SignersInput = (props) => { value={selected} onChange={onChange} closeMenuOnSelect={false} + required={props.required} /> </div> <div diff --git a/apps/OpenSign/src/components/fields/TimeWidget.js b/apps/OpenSign/src/components/fields/TimeWidget.js deleted file mode 100644 index 660840fa7..000000000 --- a/apps/OpenSign/src/components/fields/TimeWidget.js +++ /dev/null @@ -1,26 +0,0 @@ -import React from "react"; -import PropTypes from "prop-types"; - -function TimeWidget(props) { - const { - onChange, - registry: { - widgets: { BaseInput } - } - } = props; - return ( - <BaseInput - type="time" - {...props} - onChange={(value) => onChange(value || undefined)} - /> - ); -} - -if (process.env.NODE_ENV !== "production") { - TimeWidget.propTypes = { - value: PropTypes.string - }; -} - -export default TimeWidget; diff --git a/apps/OpenSign/src/constant/const.js b/apps/OpenSign/src/constant/const.js index 33e711591..b2401db56 100644 --- a/apps/OpenSign/src/constant/const.js +++ b/apps/OpenSign/src/constant/const.js @@ -1,5 +1,6 @@ export const contactCls = "contracts_Contactbook"; export const templateCls = "contracts_Template"; +export const documentCls = "contracts_Document"; export const rejectBtn = "bg-[#ffffff] rounded-sm shadow-md text-[12px] font-semibold uppercase text-black py-1.5 px-4 focus:outline-none text-center border-[1px] border-[#b4b4b4]"; export const submitBtn = diff --git a/apps/OpenSign/src/json/FormJson.js b/apps/OpenSign/src/json/FormJson.js index eaa5818b3..a8f8bc792 100644 --- a/apps/OpenSign/src/json/FormJson.js +++ b/apps/OpenSign/src/json/FormJson.js @@ -1,249 +1,34 @@ -import Parse from "parse"; +import { documentCls, templateCls } from "../constant/const"; export const formJson = (id) => { let formData; //json form for signYourself if (id === "sHAnZphf69") { formData = { - jsonSchema: { - title: "Sign Yourself", - description: "", - type: "object", - required: ["URL", "Name"], - properties: { - URL: { - type: "string", - title: "Select Document", - filetypes: [], - maxfilesizeKB: "10000", - uploadtype: "regular", - helpbody: "", - helplink: "" - }, - Name: { - type: "string", - title: "Title", - maxLength: 50 - }, - Description: { - type: "string", - title: "Description", - maxLength: 500 - }, - Folder: { - title: "Folder", - parent: null, - data: { - ClassName: "contracts_Document", - FolderNameField: "Name", - FolderTypeField: "Type", - FolderTypeValue: "Folder", - FolderDescription: "Description", - ParentFolderField: "Folder", - FormId: "YjIB7W7Xs6", - Query: 'where={"Folder":{"$exists":false},"Type":"Folder"}' - } - }, - ExtUserPtr: { - data: { - valueKey: "objectId", - isPointer: true - } - } - } - }, - uiSchema: { - URL: { - "ui:field": "FileUpload" - }, - Description: { - "ui:widget": "textarea", - "ui:options": { - rows: 2 - } - }, - Note: { - "ui:widget": "textarea", - "ui:options": { - rows: 2 - } - }, - Folder: { - "ui:field": "FolderComponent" - }, - ExtUserPtr: { - "ui:field": "HiddenField" - } - }, - userSchema: {}, - rules: null, - noValidate: false, - liveValidate: false, - isRegisterForm: false, - help: { htmlbody: "" }, - description: "", - class: "contracts_Document", - buttons: { - add: { - resetText: "Reset", - submitText: "Submit" - }, - edit: { submitText: "Update", cancelText: "Cancel" } - }, - formACL: { - "#currentUser#": { read: true, write: true }, - "*": { read: true, write: true } - }, - redirect_id: - "remoteUrl=aHR0cHM6Ly9xaWstYWktb3JnLmdpdGh1Yi5pby9TaWduLU1pY3JvYXBwVjIvcmVtb3RlRW50cnkuanM=&moduleToLoad=AppRoutes&remoteName=signmicroapp/signaturePdf", - success_message: "Success!", - success_redirect: "Microapp", - validFunction: - "ZnVuY3Rpb24gdmFsaWRhdGUoZm9ybURhdGEsIGVycm9ycykgeyBpZiAoZm9ybURhdGEucGFzczEgIT09IGZvcm1EYXRhLnBhc3MyKSB7IGVycm9ycy5wYXNzMi5hZGRFcnJvcignUGFzc3dvcmRzIGRvbid0IG1hdGNoJyk7IH0gcmV0dXJuIGVycm9yczsgfQ==" + title: "Sign Yourself", + redirectRoute: "signaturePdf", + msgVar: "Document", + Cls: documentCls }; - return formData; } //json form for request signature else if (id === "8mZzFxbG1z") { - const user = Parse.User.current(); - const userPtr = JSON.stringify({ - __type: "Pointer", - className: "_User", - objectId: user.id - }); formData = { - jsonSchema: { - title: "Request signatures", - description: "", - type: "object", - required: ["URL", "Name", "Note", "TimeToCompleteDays", "Signers"], - properties: { - URL: { - type: "string", - title: "Select Document", - filetypes: [], - maxfilesizeKB: "5000", - uploadtype: "regular", - helpbody: "", - helplink: "" - }, - Name: { - type: "string", - title: "Title", - maxLength: 100 - }, - Description: { - type: "string", - title: "Description", - maxLength: 500 - }, - Signers: { - type: "array", - title: "Signers", - isSortable: false, - selectAll: false, - selectedData: null, - data: { - class: "contracts_Contactbook", - displayKey: "Name", - valueKey: "objectId", - query: `where={"CreatedBy":${userPtr},"IsDeleted":{"$ne":true}}&keys=Name`, - isPointer: true, - helpbody: "", - helplink: "", - quickAddFormId: "qUGywSWd8e" - } - }, - Note: { - type: "string", - title: "Note", - default: "Please review and sign this document", - maxLength: 500 - }, - Folder: { - title: "Folder", - data: { - ClassName: "contracts_Document", - FolderNameField: "Name", - FolderTypeField: "Type", - FolderTypeValue: "Folder", - FolderDescription: "Description", - ParentFolderField: "Folder", - FormId: "YjIB7W7Xs6", - Query: 'where={"Folder":{"$exists":false},"Type":"Folder"}' - } - }, - TimeToCompleteDays: { - type: "number", - title: "Time To Complete (Days)", - default: 15, - maxLength: 5000 - }, - ExtUserPtr: { - data: { - valueKey: "objectId", - isPointer: true - } - } - } - }, - uiSchema: { - URL: { - "ui:field": "FileUpload" - }, - Description: { - "ui:widget": "textarea", - "ui:options": { - rows: 2 - } - }, - Note: { - "ui:widget": "textarea", - "ui:options": { - rows: 2 - } - }, - Signers: { - "ui:field": "MultiSelectField" - }, - Folder: { - "ui:field": "FolderComponent" - }, - TimeToCompleteDays: { - "ui:placeholder": "No. of days", - "ui:widget": "updown" - }, - ExtUserPtr: { - "ui:field": "HiddenField" - } - }, - userSchema: {}, - rules: null, - noValidate: false, - liveValidate: false, - isRegisterForm: false, - help: { htmlbody: "" }, - description: "", - class: "contracts_Document", - buttons: { - add: { - resetText: "Reset", - submitText: "Submit" - }, - edit: { submitText: "Update", cancelText: "Cancel" } - }, - formACL: { - "#currentUser#": { read: true, write: true }, - "*": { read: true, write: true } - }, - redirect_id: - "remoteUrl=aHR0cHM6Ly9xaWstYWktb3JnLmdpdGh1Yi5pby9TaWduLU1pY3JvYXBwVjIvcmVtb3RlRW50cnkuanM=&moduleToLoad=AppRoutes&remoteName=signmicroapp/placeHolderSign", - success_message: "Success!", - success_redirect: "Microapp", - validFunction: - "ZnVuY3Rpb24gdmFsaWRhdGUoZm9ybURhdGEsIGVycm9ycykgeyBpZiAoZm9ybURhdGEucGFzczEgIT09IGZvcm1EYXRhLnBhc3MyKSB7IGVycm9ycy5wYXNzMi5hZGRFcnJvcignUGFzc3dvcmRzIGRvbid0IG1hdGNoJyk7IH0gcmV0dXJuIGVycm9yczsgfQ==" + title: "Request Signature", + msgVar: "Document", + redirectRoute: "placeHolderSign", + Cls: documentCls, + signers: true + }; + return formData; + } //json form for template + else if (id === "template") { + formData = { + title: "New Template", + redirectRoute: "template", + msgVar: "Template", + Cls: templateCls }; - return formData; } //json form for create new folder diff --git a/apps/OpenSign/src/primitives/TemplateForm.js b/apps/OpenSign/src/primitives/TemplateForm.js deleted file mode 100644 index 5fa592870..000000000 --- a/apps/OpenSign/src/primitives/TemplateForm.js +++ /dev/null @@ -1,336 +0,0 @@ -import React, { useState } from "react"; -import sanitizeFileName from "./sanitizeFileName"; -import Parse from "parse"; -import DropboxChooser from "../components/fields/DropboxChoose"; -import Alert from "./Alert"; -import SelectFolder from "../components/fields/SelectFolder"; -// import SignersInput from "../components/fields/SignersInput"; -import Title from "../components/Title"; -import { useNavigate } from "react-router-dom"; -import { templateCls } from "../constant/const"; - -const TemplateForm = () => { - const navigate = useNavigate(); - const [signers, setSigners] = useState([]); - const [folder, setFolder] = useState({ ObjectId: "", Name: "" }); - const [formData, setFormData] = useState({ - Name: "", - Description: "", - Note: "Please review and sign this document" - }); - const [fileupload, setFileUpload] = useState([]); - const [fileload, setfileload] = useState(false); - const [percentage, setpercentage] = useState(0); - const [isAlert, setIsAlert] = useState(false); - const [isSubmit, setIsSubmit] = useState(false); - const [isErr, setIsErr] = useState(""); - const handleStrInput = (e) => { - setFormData({ ...formData, [e.target.name]: e.target.value }); - }; - - const handleFileInput = (e) => { - setpercentage(0); - try { - let files = e.target.files; - if (typeof files[0] !== "undefined") { - const mb = Math.round(files[0].bytes / Math.pow(1024, 2)); - if (mb > 10) { - alert( - `The selected file size is too large. Please select a file less than ${Math.round( - 10 - )} MB` - ); - return; - } - - handleFileUpload(files[0]); - } else { - alert("Please select file."); - return false; - } - } catch (error) { - alert(error.message); - return false; - } - }; - - const handleFileUpload = async (file) => { - Parse.serverURL = process.env.REACT_APP_SERVERURL; - Parse.initialize(process.env.REACT_APP_APPID); - setfileload(true); - const fileName = file.name; - const name = sanitizeFileName(fileName); - const pdfFile = file; - const parseFile = new Parse.File(name, pdfFile); - - try { - const response = await parseFile.save({ - progress: (progressValue, loaded, total, { type }) => { - if (type === "upload" && progressValue !== null) { - const percentCompleted = Math.round((loaded * 100) / total); - setpercentage(percentCompleted); - } - } - }); - - // The response object will contain information about the uploaded file - // You can access the URL of the uploaded file using response.url() - setFileUpload(response.url()); - setfileload(false); - if (response.url()) { - return response.url(); - } - } catch (error) { - setfileload(false); - setpercentage(0); - console.error("Error uploading file:", error); - } - }; - - const dropboxSuccess = async (files) => { - setfileload(true); - const file = files[0]; - const url = file.link; - const mb = Math.round(file.bytes / Math.pow(1024, 2)); - - if (mb > 10) { - setTimeout(() => { - alert( - `The selected file size is too large. Please select a file less than 10 MB` - ); - }, 500); - return; - } else { - const name = sanitizeFileName(file.name); - - const parseFile = new Parse.File(name, { uri: url }); - - try { - const response = await parseFile.save({ - progress: (progressValue, loaded, total, { type }) => { - if (type === "upload" && progressValue !== null) { - const percentCompleted = Math.round((loaded * 100) / total); - setpercentage(percentCompleted); - } - } - }); - setFileUpload(response.url()); - setfileload(false); - - if (response.url()) { - return response.url(); - } - } catch (error) { - setfileload(false); - setpercentage(0); - console.error("Error uploading file:", error); - } - } - }; - const dropboxCancel = async () => {}; - const handleSubmit = async (e) => { - e.preventDefault(); - setIsSubmit(true); - try { - const currentUser = Parse.User.current(); - const template = new Parse.Object(templateCls); - Object.entries(formData).forEach((item) => - template.set(item[0], item[1]) - ); - template.set("URL", fileupload); - template.set("CreatedBy", Parse.User.createWithoutData(currentUser.id)); - if (folder && folder.ObjectId) { - template.set("Folder", { - __type: "Pointer", - className: templateCls, - objectId: folder.ObjectId - }); - } - if (signers && signers.length > 0) { - template.set("Signers", signers); - } - const ExtCls = JSON.parse(localStorage.getItem("Extand_Class")); - template.set("ExtUserPtr", { - __type: "Pointer", - className: "contracts_Users", - objectId: ExtCls[0].objectId - }); - - const res = await template.save(); - if (res) { - setSigners([]); - setFolder({ ObjectId: "", Name: "" }); - setFormData({ - Name: "", - Description: "", - Note: "" - }); - setFileUpload([]); - setpercentage(0); - navigate( - "/asmf/remoteUrl=aHR0cHM6Ly9xaWstYWktb3JnLmdpdGh1Yi5pby9TaWduLU1pY3JvYXBwVjIvcmVtb3RlRW50cnkuanM=&moduleToLoad=AppRoutes&remoteName=signmicroapp/template/" + - res.id - ); - } - } catch (err) { - console.log("err ", err); - setIsErr(true); - } finally { - setIsAlert(true); - setTimeout(() => { - setIsAlert(false); - }, 1000); - setIsSubmit(false); - } - }; - - const handleFolder = (data) => { - setFolder(data); - }; - // const handleSigners = (data) => { - // if (data && data.length > 0) { - // const updateSigners = data.map((x) => ({ - // __type: "Pointer", - // className: "contracts_Contactbook", - // objectId: x - // })); - // setSigners(updateSigners); - // } - // }; - - const handleReset = () => { - setSigners([]); - setFolder({ ObjectId: "", Name: "" }); - setFormData({ - Name: "", - Description: "", - Note: "" - }); - setFileUpload([]); - setpercentage(0); - }; - return ( - <div className="shadow-md rounded my-2 p-3 bg-[#ffffff] md:border-[1px] md:border-gray-600/50"> - <Title title="New Template" /> - {isAlert && ( - <Alert type={isErr ? "danger" : "success"}> - {isErr - ? "Something went wrong please try again!" - : "Template created successfully!"} - </Alert> - )} - <form onSubmit={handleSubmit}> - <h1 className="text-[20px] font-semibold mb-4">New Template</h1> - {fileload && ( - <div className="flex items-center gap-x-2"> - <div className="h-2 rounded-full w-[200px] md:w-[400px] bg-gray-200"> - <div - className="h-2 rounded-full bg-blue-500" - style={{ width: `${percentage}%` }} - ></div> - </div> - <span className="text-black text-sm">{percentage}%</span> - </div> - )} - <div className="text-xs"> - <label className="block"> - File<span className="text-red-500 text-[13px]">*</span> - </label> - {fileupload.length > 0 ? ( - <div className="flex gap-2 justify-center items-center"> - <div className="flex justify-between items-center px-2 py-2 w-full font-bold rounded border-[1px] border-[#ccc] text-gray-500 bg-white text-[13px]"> - <div className="break-all"> - file selected : {fileupload?.split("/")[3]?.split("_")[1]} - </div> - <div - onClick={() => { - setFileUpload([]); - }} - className="cursor-pointer px-[10px] text-[20px] font-bold bg-white text-red-500" - > - <i className="fa-solid fa-xmark"></i> - </div> - </div> - {process.env.REACT_APP_DROPBOX_API_KEY && ( - <DropboxChooser - onSuccess={dropboxSuccess} - onCancel={dropboxCancel} - /> - )} - </div> - ) : ( - <div className="flex gap-2 justify-center items-center"> - <input - type="file" - className="bg-white px-2 py-1.5 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" - onChange={(e) => handleFileInput(e)} - accept="application/pdf,application/vnd.ms-excel" - required - /> - {process.env.REACT_APP_DROPBOX_API_KEY && ( - <DropboxChooser - onSuccess={dropboxSuccess} - onCancel={dropboxCancel} - /> - )} - </div> - )} - </div> - <div className="text-xs mt-2"> - <label className="block"> - Title<span className="text-red-500 text-[13px]">*</span> - </label> - <input - name="Name" - className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" - value={formData.Name} - onChange={(e) => handleStrInput(e)} - required - /> - </div> - <div className="text-xs mt-2"> - <label className="block"> - Note<span className="text-red-500 text-[13px]">*</span> - </label> - <input - name="Note" - className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" - value={formData.Note} - onChange={(e) => handleStrInput(e)} - required - /> - </div> - <div className="text-xs mt-2"> - <label className="block">Description</label> - <input - name="Description" - className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" - value={formData.Description} - onChange={(e) => handleStrInput(e)} - /> - </div> - {/* <SignersInput onChange={handleSigners} /> */} - <SelectFolder onSuccess={handleFolder} folderCls={templateCls} /> - <div className="flex items-center mt-3 gap-2 text-white"> - <button - className={`${ - isSubmit && "cursor-progress" - } bg-[#1ab6ce] rounded-sm shadow-md text-[14px] font-semibold uppercase text-white py-1.5 px-2.5 focus:outline-none`} - type="submit" - disabled={isSubmit} - > - Submit - </button> - <div - className="bg-[#188ae2] rounded-sm shadow-md text-[14px] font-semibold uppercase text-white py-1.5 px-2.5 text-center ml-[2px] focus:outline-none" - onClick={() => handleReset()} - > - Reset - </div> - </div> - </form> - </div> - ); -}; - -export default TemplateForm; diff --git a/apps/OpenSign/src/redux/actions/index.js b/apps/OpenSign/src/redux/actions/index.js index afec8161d..fae7642ed 100644 --- a/apps/OpenSign/src/redux/actions/index.js +++ b/apps/OpenSign/src/redux/actions/index.js @@ -124,8 +124,7 @@ export const login = (username, password) => async (dispatch) => { const currentUser = Parse.User.current(); await Parse.Cloud.run("getUserDetails", { email: currentUser.get("email") - }) - .then( + }).then( (results) => { let userinfo = results.toJSON(); if (userinfo.TenantId) { @@ -257,12 +256,6 @@ export const removeFromCart = (val) => async (dispatch) => { }); }; -export const onChangeLevel1Dropdown = (id, name) => async (dispatch) => { - localStorage.setItem(`_dd${name}`, id); - let _data = { [name]: `${id}` }; - dispatch({ type: "Level1_Dropdown", payload: _data }); -}; - export const onChangeLevel2Dropdown = (id, name) => async (dispatch) => { localStorage.setItem(`_dd${name}`, id); let _data = { [name]: `${id}` }; diff --git a/apps/OpenSign/src/routes/Form.js b/apps/OpenSign/src/routes/Form.js index 2c6c67709..da272e27f 100644 --- a/apps/OpenSign/src/routes/Form.js +++ b/apps/OpenSign/src/routes/Form.js @@ -1,1244 +1,243 @@ -import React, { Component } from "react"; -import { connect } from "react-redux"; -import { - removeState, - removeLevel2State, - removeLevel3State -} from "../redux/actions/index"; -import Engine from "json-rules-engine-simplified"; -import applyRules from "rjsf-conditionals"; -import Form from "@rjsf/core"; -import validator from "@rjsf/validator-ajv8"; -import LayoutField from "../components/fields/Rjsf-layout"; -import "../styles/form.css"; -import "../styles/toast.css"; -import Parse from "parse"; -import "../styles/loader.css"; -import TimeWidget from "../components/fields/TimeWidget"; -import axios from "axios"; +import React, { useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; -import HiddenField from "../components/fields/HiddenField"; -import MultiSelectField from "../components/fields/MultiSelectField"; -import ErrorBoundary from "../components/ErrorBoundary"; -import FileUpload from "../components/fields/FileUpload"; -import TreeWidget from "../components/TreeWidget"; -import parse from "html-react-parser"; -import Title from "../components/Title"; import { formJson } from "../json/FormJson"; -import TemplateForm from "../primitives/TemplateForm"; -const widget = { - TimeWidget: TimeWidget -}; -const fields = () => { - return { - layout: LayoutField, - FileUpload: FileUpload, - HiddenField: HiddenField, - MultiSelectField: MultiSelectField, - FolderComponent: TreeWidget - }; -}; +import AddUser from "../components/AddUser"; +import sanitizeFileName from "../primitives/sanitizeFileName"; +import Parse from "parse"; +import DropboxChooser from "../components/fields/DropboxChoose"; +import Alert from "../primitives/Alert"; +import SelectFolder from "../components/fields/SelectFolder"; +import SignersInput from "../components/fields/SignersInput"; +import Title from "../components/Title"; -function FormBuilderFn(props) { +function Form() { const { id } = useParams(); - const navigate = useNavigate(); - if (id === "template") { - return <TemplateForm />; + + if (id === "lM0xRnM3iE") { + return <AddUser />; } else { - return ( - <FormBuilder - removeState={props.removeState} - removeLevel2State={props.removeLevel2State} - removeLevel3State={props.removeLevel3State} - id={id} - navigate={navigate} - /> - ); + const config = formJson(id) || {}; + return <Forms {...config} />; } } -class FormBuilder extends Component { - state = { - schema: {}, - ui_schema: {}, - extraActions: undefined, - rules: [], - isAppRequest: false, - formData: {}, - persistentFields: [], - successMassage: "Record inserted successfully.", - title: "", - active: true, - buttons: {}, - schemaState: {}, - noValidate: false, - liveValidate: false, - _validate: null, - userSchema: {}, - loading: false, - parseBaseUrl: localStorage.getItem("baseUrl"), - parseAppId: localStorage.getItem("parseAppId"), - toastColor: "#5cb85c", - toastDescription: "", - redirect_type: "", - redirect_id: "", - FormACL: null, - help: "", - link: "" + +const Forms = (props) => { + const navigate = useNavigate(); + const [signers, setSigners] = useState([]); + const [folder, setFolder] = useState({ ObjectId: "", Name: "" }); + const [formData, setFormData] = useState({ + Name: "", + Description: "", + Note: "Please review and sign this document", + TimeToCompleteDays: 15 + }); + const [fileupload, setFileUpload] = useState([]); + const [fileload, setfileload] = useState(false); + const [percentage, setpercentage] = useState(0); + const [isAlert, setIsAlert] = useState(false); + const [isSubmit, setIsSubmit] = useState(false); + const [isErr, setIsErr] = useState(""); + const handleStrInput = (e) => { + setFormData({ ...formData, [e.target.name]: e.target.value }); }; - async getForm(id) { - this.setState({ - loading: true - }); + const handleFileInput = (e) => { + setpercentage(0); try { - const results = formJson(id); - // console.log("custom result",results) - if (results) { - const resultjson = results; - if (resultjson.userSchema !== undefined) { - this.setState({ - userSchema: resultjson.userSchema - }); + let files = e.target.files; + if (typeof files[0] !== "undefined") { + const mb = Math.round(files[0].bytes / Math.pow(1024, 2)); + if (mb > 10) { + alert( + `The selected file size is too large. Please select a file less than ${Math.round( + 10 + )} MB` + ); + return; } - for (let [value] of Object.entries(resultjson.jsonSchema.properties)) { - if (typeof value === "object") { - for (let [k, v] of Object.entries(value)) { - if (k === "format" && v === "date") { - let today = new Date(); - let date = - today.getFullYear() + - "-" + - ("0" + (today.getMonth() + 1)).slice(-2) + - "-" + - ("0" + today.getDate()).slice(-2); - value.default = date; - } - if (k === "component" && v === "DateTime") { - value.default = new Date().toISOString(); - } - } - } - } - let txt, - link, - successMsg, - _rules = [], - persistentFields = [], - _extraActions = {}; - if (resultjson.help) { - if (resultjson.help.htmlbody) { - txt = resultjson.help.htmlbody; - } - if (resultjson.help.link) { - link = resultjson.help.link; - } - } - if (resultjson.rules) { - _rules = resultjson.rules; - } - if (resultjson.persistentFields) { - persistentFields = resultjson.persistentFields; - } - if (resultjson.extraActions) { - _extraActions = this.setExtraActions(resultjson.extraActions); - } - if (resultjson.success_message) { - successMsg = resultjson.success_message; - } else { - successMsg = this.state.successMassage; - } - let _jsonSchema = JSON.stringify(resultjson.jsonSchema); - _jsonSchema = _jsonSchema.replace("#$", "$"); - _jsonSchema = _jsonSchema.replace("#*", "$"); - _jsonSchema = _jsonSchema.replace("_DOT_", "."); - let _replaceJSONSchema = JSON.parse(_jsonSchema); - this.setState({ - redirect_type: resultjson.success_redirect, - redirect_id: resultjson.redirect_id, - FormACL: resultjson.formACL, - help: txt, - link: link, - persistentFields: persistentFields, - successMassage: successMsg, - buttons: resultjson.buttons.add, - schemaState: _replaceJSONSchema, - ui_schema: resultjson.uiSchema, - rules: _rules, - extraActions: _extraActions, - title: resultjson.class, - _validate: resultjson.validFunction, - noValidate: resultjson.noValidate, - liveValidate: resultjson.liveValidate && resultjson.liveValidate, - loading: false - }); - localStorage.setItem( - "jsonschema", - JSON.stringify(resultjson.jsonSchema) - ); + handleFileUpload(files[0]); } else { - alert("form not found"); + alert("Please select file."); + return false; } - } catch (e) { - if (e.message === "Invalid session token") { - let appdata = localStorage.getItem("userSettings"); - let applogo = localStorage.getItem("appLogo"); - let appName = localStorage.getItem("appName"); - let defaultmenuid = localStorage.getItem("defaultmenuid"); - let PageLanding = localStorage.getItem("PageLanding"); - let domain = localStorage.getItem("domain"); - let _appName = localStorage.getItem("_appName"); - let baseUrl = localStorage.getItem("BaseUrl12"); - let appid = localStorage.getItem("AppID12"); - localStorage.clear(); - localStorage.setItem("appLogo", applogo); - localStorage.setItem("appName", appName); - localStorage.setItem("_appName", _appName); - localStorage.setItem("defaultmenuid", defaultmenuid); - localStorage.setItem("PageLanding", PageLanding); - localStorage.setItem("domain", domain); - localStorage.setItem("userSettings", appdata); - localStorage.setItem("BaseUrl12", baseUrl); - localStorage.setItem("AppID12", appid); - this.props.navigate(`/`); - } - console.log(e.message); - console.error("Problem", e); - this.setState({ - loading: false - }); - } - } - - wrap = (s) => "{ return " + s + " };"; - - // func = new Function(wrap(body)); - - dynamicValidate = (formData, errors) => { - try { - let body = atob(this.state._validate); - let res = new Function(this.wrap(body)) - .call(null) - .call(null, formData, errors); - return res; } catch (error) { - console.log(error); + alert(error.message); + return false; } }; - setExtraActions = (actions) => { + const handleFileUpload = async (file) => { + Parse.serverURL = process.env.REACT_APP_SERVERURL; + Parse.initialize(process.env.REACT_APP_APPID); + setfileload(true); + const fileName = file.name; + const name = sanitizeFileName(fileName); + const pdfFile = file; + const parseFile = new Parse.File(name, pdfFile); + try { - let result = {}; - Object.entries(actions).forEach(([key, value]) => { - let body = atob(value); - let res = new Function(this.wrap(body)).call(null); - result[key] = res; + const response = await parseFile.save({ + progress: (progressValue, loaded, total, { type }) => { + if (type === "upload" && progressValue !== null) { + const percentCompleted = Math.round((loaded * 100) / total); + setpercentage(percentCompleted); + } + } }); - return result; + + // The response object will contain information about the uploaded file + // You can access the URL of the uploaded file using response.url() + setFileUpload(response.url()); + setfileload(false); + if (response.url()) { + return response.url(); + } } catch (error) { - console.log(error); + setfileload(false); + setpercentage(0); + console.error("Error uploading file:", error); } }; - handleSubmit = async ({ formData }) => { - this.setState({ active: false, loading: true }); - if ( - this.state.userSchema && - Object.entries(this.state.userSchema).length !== 0 && - this.state.userSchema.constructor === Object - ) { - try { - let RowData = formData; - RowData && - Object.entries(RowData).forEach(([key, value]) => { - if (typeof value === "string") { - RowData[key] = value.trim(); - } - }); - let UserData = {}; - let RoleField = ""; - let _scanData = this.state.schemaState; - if (_scanData.dependencies) { - Object.keys(_scanData.dependencies).forEach((key) => { - if (_scanData.dependencies[key].oneOf) { - _scanData.dependencies[key].oneOf.forEach((val) => { - Object.keys(val.properties).forEach((k) => { - if (typeof val.properties[k] === "object") { - if (val.properties[k].format === "date") { - if (RowData[k]) { - let newdate = new Date(RowData[k]); - RowData[k] = newdate; - } - } - if (val.properties[k].component === "HtmlEditor") { - if (RowData[k]) { - let newHtml = RowData[k] - .replace(/<p[^>]*>/g, "") - .replace(/<\/p>/g, " "); - RowData[k] = newHtml; - } - } - if (val.properties[k].component === "DateTime") { - if (RowData[k]) { - let newDate11 = new Date(RowData[k]); - RowData[k] = newDate11; - } - } - if (val.properties[k].component === "CurrencyInput") { - if (val.properties[k].currencyColumn) { - RowData[`${val.properties[k].currencyColumn}`] = - val.properties[k].defaultcurrency; - } - } - if (val.properties[k].type === "string") { - if (typeof RowData[k] === "string") - RowData[k] = RowData[k].trim(); - } - if (val.properties[k].data !== undefined) { - if (val.properties[k].data.isPointer) { - let pointer = undefined; - if (val.properties[k].data.class) { - if (val.properties[k].data.savePointerClass) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: - val.properties[k].data.savePointerClass, - objectId: RowData[k] - }; - } - } else { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: val.properties[k].data.class, - objectId: RowData[k] - }; - } - } - } else { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: localStorage.getItem("extended_class"), - objectId: RowData[k] - }; - } - } - RowData[k] = pointer; - } - if (val.properties[k].data.FolderTypeValue) { - if (RowData[k]) { - let obj = { - __type: "Pointer", - className: val.properties[k].data.ClassName, - objectId: RowData[k] - }; - RowData[k] = obj; - } - } - } - } - }); - }); - } - }); - } - let _userScheama = this.state.userSchema; - Object.keys(_scanData).forEach(function (key) { - let _dd = _scanData[key]; - typeof _dd === "object" && - Object.keys(_dd).forEach(function (k) { - if (_dd[k].type === "array" && _dd[k].items) { - let _prop = _dd[k].items.properties; + const dropboxSuccess = async (files) => { + setfileload(true); + const file = files[0]; + const url = file.link; + const mb = Math.round(file.bytes / Math.pow(1024, 2)); - if (_prop && Array.isArray(RowData[k])) { - let newRow = []; - RowData[k].forEach((t) => { - let _newObj = t; - if (typeof t === "object") { - Object.keys(_prop).forEach(function (l) { - if (_prop[l].data && _prop[l].data.isPointer) { - if (typeof t[l] === "object") { - let obj = { - __type: "Pointer", - className: _prop[l].data.class, - objectId: t[l].objectId - }; - _newObj = { ..._newObj, [l]: obj }; - } else { - let obj = { - __type: "Pointer", - className: _prop[l].data.class, - objectId: t[l] - }; - _newObj = { ..._newObj, [l]: obj }; - } - } - }); - } - newRow.push(_newObj); - }); - RowData[k] = newRow; - } - } - - if (_dd[k].component === "AutoSuggest" && _dd[k].isPointer) { - if (RowData[k]) { - let pointer = { - __type: "Pointer", - className: _dd[k].class, - objectId: RowData[k] - }; - RowData[k] = pointer; - } - } - if (_dd[k].format === "date") { - let newdate = new Date(RowData[k]); - RowData[k] = newdate; - } - if (_dd[k].component === "CurrencyInput") { - RowData[`${_dd[k].currencyColumn}`] = _dd[k].defaultcurrency; - } - if (_dd[k].component === "HtmlEditor") { - if (RowData[k]) { - let newHtml = RowData[k] - .replace(/<p[^>]*>/g, "") - .replace(/<\/p>/g, " "); - RowData[k] = newHtml; - } - } - if (_dd[k].component === "DateTime") { - let newDate; - if (!RowData[k]) { - newDate = new Date(); - } else { - newDate = new Date(RowData[k]); - } - RowData[k] = newDate; - } - if (_dd[k].data !== undefined) { - if (_dd[k].data.isPointer) { - let pointer = undefined; - if (_dd[k].data.savePointerClass) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: _dd[k].data.savePointerClass, - objectId: RowData[k] - }; - RowData[k] = pointer; - } - } else if (RowData[k]) { - if (_dd[k].data.class) { - pointer = { - __type: "Pointer", - className: _dd[k].data.class, - objectId: RowData[k] - }; - } else { - pointer = { - __type: "Pointer", - className: localStorage.getItem("extended_class"), - objectId: RowData[k] - }; - } - - RowData[k] = pointer; - } - } - if (_dd[k].data.FolderTypeValue) { - if (RowData[k]) { - let obj = { - __type: "Pointer", - className: _dd[k].data.ClassName, - objectId: RowData[k] - }; - RowData[k] = obj; - } - } - } - if (_dd[k].type === "string") { - let d = RowData[k]; - if (typeof d === "string") { - RowData[k] = d.trim(); - } - } - }); - }); - - Object.keys(_userScheama).forEach(function (kkey) { - Object.keys(RowData).forEach(function (_k) { - if (_userScheama[kkey].startsWith("$")) { - let _uuu = _userScheama[kkey].replace("$", ""); - if (kkey === "Role" || kkey === "role") { - if (RowData[_uuu] === RowData[_k]) { - RoleField = RowData[_uuu]; - } - } else if (_uuu === _k) { - UserData[kkey] = RowData[_k]; - } - } else { - RoleField = _userScheama[kkey]; - } - }); - }); - Parse.serverURL = this.state.parseBaseUrl; - Parse.initialize(this.state.parseAppId); - var _users = Parse.Object.extend("User"); - var _user = new _users(); - let _uname = UserData.name; - _user.set("name", _uname.toString().trim()); - if (UserData.username) { - let _u_un = UserData.username; - _user.set("username", _u_un.toString().trim()); - if (UserData.email) { - let _email = UserData.email; - _user.set("email", _email.trim()); - } - } else if (UserData.email) { - let _email = UserData.email; - _user.set("email", _email.trim()); - _user.set("username", _email.trim()); - } else { - _user.set("username", UserData.phone.toString().trim()); - } - _user.set("phone", UserData.phone); - _user.set("password", UserData.password); - _user.save().then( - (u) => { - let roleurl = `${this.state.parseBaseUrl}functions/AddUserToRole`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": this.state.parseAppId, - sessionToken: localStorage.getItem("accesstoken") - }; - let body = { - appName: localStorage.getItem("_appName"), - roleName: RoleField, - userId: u.id - }; - axios.post(roleurl, body, { headers: headers }).then(() => { - const currentUser = Parse.User.current(); - let _fname = this.state.title; - var forms = Parse.Object.extend(_fname); - var form = new forms(); - form.set( - "CreatedBy", - Parse.User.createWithoutData(currentUser.id) - ); - if (localStorage.getItem("TenetId")) { - form.set("TenantId", { - __type: "Pointer", - className: "partners_Tenant", - objectId: localStorage.getItem("TenetId") - }); - } - form.set("UserId", u); - form.set("UserRole", RoleField); - if (this.state["FormACL"]) { - let ACL = {}; - for (let [key, value] of Object.entries( - this.state["FormACL"] - )) { - if (key === "*") { - ACL[key] = value; - } - if (key === "#currentUser#") { - ACL[Parse.User.current().id] = value; - } - if (key.startsWith("role")) { - ACL[key] = value; - } - } - form.setACL(new Parse.ACL(ACL)); - } - form.save(RowData).then( - () => { - let filtered = {}; - if (this.state.redirect_type === "clearData") { - if ( - this.state.persistentFields && - this.state.persistentFields.length - ) { - filtered = Object.keys(RowData) - .filter((key) => - this.state.persistentFields.includes(key) - ) - .reduce((obj, key) => { - obj[key] = RowData[key]; - return obj; - }, {}); - } - } else { - RowData = {}; - } - this.setState( - { - formData: filtered, - active: true, - loading: false, - toastColor: "#5cb85c", - toastDescription: this.state.successMassage - }, - () => { - let redirect_type = this.state.redirect_type; - let redirect_id = this.state.redirect_id; - this.props.removeState(); - this.props.removeLevel2State(); - this.props.removeLevel3State(); - var x = document.getElementById("snackbar"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - if (redirect_type === "Form") { - this.props.navigate(`/form/${redirect_id}`); - } else if (redirect_type === "Report") { - this.props.navigate(`/report/${redirect_id}`); - } else if (redirect_type === "Dashboard") { - this.props.navigate(`/dashboard/${redirect_id}`); - } else if (redirect_type === "Url") { - window.location = redirect_id; - } else if (redirect_type === "Microapp") { - this.props.navigate(`/asmf/${redirect_id}`); - } - }, 2000); - } - ); - }, - (error) => { - console.log("error", error.message); - this.setState({ - loading: false, - active: true, - toastColor: "#d9534f", - toastDescription: error.message - }); - - var x = document.getElementById("snackbar"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 2000); - } - ); - }); - }, - async (error) => { - if (error.code === 202) { - let params; - if (UserData.username) { - params = { username: UserData.username }; - } else if (UserData.email) { - params = { email: UserData.email }; - } else { - params = { username: UserData.phone }; - } - const userRes = await Parse.Cloud.run("getUserId", params); - try { - let _emp = { - __type: "Pointer", - className: "_User", - objectId: userRes.id - }; - let roleurl = `${this.state.parseBaseUrl}functions/AddUserToRole`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": this.state.parseAppId, - sessionToken: localStorage.getItem("accesstoken") - }; - let body = { - appName: localStorage.getItem("_appName"), - roleName: RoleField, - userId: userRes.id - }; - await axios - .post(roleurl, body, { headers: headers }) - .then(() => { - const currentUser = Parse.User.current(); - let _fname = this.state.title; - var forms = Parse.Object.extend(_fname); - var form = new forms(); - form.set( - "CreatedBy", - Parse.User.createWithoutData(currentUser.id) - ); - if (localStorage.getItem("TenetId")) { - form.set("TenantId", { - __type: "Pointer", - className: "partners_Tenant", - objectId: localStorage.getItem("TenetId") - }); - } - form.set("UserId", _emp); - form.set("UserRole", RoleField); - if (this.state["FormACL"]) { - let ACL = {}; - for (let [key, value] of Object.entries( - this.state["FormACL"] - )) { - if (key === "*") { - ACL[key] = value; - } - if (key === "#currentUser#") { - ACL[Parse.User.current().id] = value; - } - if (key.startsWith("role")) { - ACL[key] = value; - } - } - form.setACL(new Parse.ACL(ACL)); - } - form.save(RowData).then( - () => { - let filtered = {}; - if (this.state.redirect_type === "clearData") { - if ( - this.state.persistentFields && - this.state.persistentFields.length - ) { - filtered = Object.keys(RowData) - .filter((key) => - this.state.persistentFields.includes(key) - ) - .reduce((obj, key) => { - obj[key] = RowData[key]; - return obj; - }, {}); - } - } else { - RowData = {}; - } - this.setState( - { - formData: filtered, - active: true, - loading: false, - toastColor: "#5cb85c", - toastDescription: this.state.successMassage - }, - () => { - let redirect_type = this.state.redirect_type; - let redirect_id = this.state.redirect_id; - this.props.removeState(); - this.props.removeLevel2State(); - this.props.removeLevel3State(); - var x = document.getElementById("snackbar"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - if (redirect_type === "Form") { - this.props.navigate(`/form/${redirect_id}`); - } else if (redirect_type === "Report") { - this.props.navigate(`/report/${redirect_id}`); - } else if (redirect_type === "Dashboard") { - this.props.navigate( - `/dashboard/${redirect_id}` - ); - } else if (redirect_type === "Url") { - window.location = redirect_id; - } else if (redirect_type === "Microapp") { - this.props.navigate(`/asmf/${redirect_id}`); - } - }, 2000); - } - ); - }, - (error) => { - this.setState({ - loading: false, - active: true, - toastColor: "#d9534f", - toastDescription: error.message - }); - - var x = document.getElementById("snackbar"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 2000); - } - ); - }); - } catch (error) { - this.setState({ - loading: false, - active: true, - toastColor: "#d9534f", - toastDescription: error.message - }); - - var x = document.getElementById("snackbar"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 2000); - } - } - } + if (mb > 10) { + setTimeout(() => { + alert( + `The selected file size is too large. Please select a file less than 10 MB` ); - } catch (e) { - console.log("Problem", e.message); - this.setState({ loading: false, active: true }); - } + }, 500); + return; } else { + const name = sanitizeFileName(file.name); + + const parseFile = new Parse.File(name, { uri: url }); + try { - let RowData = formData; - let _scanData = this.state.schemaState; - if (_scanData.dependencies) { - Object.keys(_scanData.dependencies).forEach((key) => { - if (_scanData.dependencies[key].oneOf) { - _scanData.dependencies[key].oneOf.forEach((val) => { - Object.keys(val.properties).forEach((k) => { - if (typeof val.properties[k] === "object") { - if (val.properties[k].format === "date") { - if (RowData[k]) { - let newdate = new Date(RowData[k]); - RowData[k] = newdate; - } - } - if (val.properties[k].component === "HtmlEditor") { - if (RowData[k]) { - let newHtml = RowData[k] - .replace(/<p[^>]*>/g, "") - .replace(/<\/p>/g, " "); - RowData[k] = newHtml; - } - } - if (val.properties[k].component === "DateTime") { - if (RowData[k]) { - let newDate11 = new Date(RowData[k]); - RowData[k] = newDate11; - } - } - if (val.properties[k].component === "CurrencyInput") { - if (val.properties[k].currencyColumn) { - RowData[`${val.properties[k].currencyColumn}`] = - val.properties[k].defaultcurrency; - } - } - if (val.properties[k].type === "string") { - if (typeof RowData[k] === "string") - RowData[k] = RowData[k].trim(); - } - if (val.properties[k].data !== undefined) { - if (val.properties[k].data.isPointer) { - let pointer = undefined; - if (val.properties[k].data.savePointerClass) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: - val.properties[k].data.savePointerClass, - objectId: RowData[k] - }; - } - } else if (val.properties[k].data.class) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: val.properties[k].data.class, - objectId: RowData[k] - }; - } - } else { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: localStorage.getItem("extended_class"), - objectId: RowData[k] - }; - } - } - - RowData[k] = pointer; - } - if (val.properties[k].data.FolderTypeValue) { - if (RowData[k]) { - let obj = { - __type: "Pointer", - className: val.properties[k].data.ClassName, - objectId: RowData[k] - }; - RowData[k] = obj; - } - } - } - } - }); - }); + const response = await parseFile.save({ + progress: (progressValue, loaded, total, { type }) => { + if (type === "upload" && progressValue !== null) { + const percentCompleted = Math.round((loaded * 100) / total); + setpercentage(percentCompleted); } - }); - } - Object.keys(_scanData).forEach(function (key) { - let _dd = _scanData[key]; - if (typeof _dd === "object") { - Object.keys(_dd).forEach(function (k) { - if (_dd[k].type === "array" && _dd[k].items) { - let _prop = _dd[k].items.properties; - if (_prop && Array.isArray(RowData[k])) { - let newRow = []; - RowData[k].forEach((t) => { - let _newObj = t; - if (typeof t === "object") { - Object.keys(_prop).forEach(function (l) { - if (_prop[l].data && _prop[l].data.isPointer) { - if (typeof t[l] === "object") { - let obj = { - __type: "Pointer", - className: _prop[l].data.class, - objectId: t[l].objectId - }; - _newObj = { ..._newObj, [l]: obj }; - } else { - let obj = { - __type: "Pointer", - className: _prop[l].data.class, - objectId: t[l] - }; - _newObj = { ..._newObj, [l]: obj }; - } - } - }); - } - newRow.push(_newObj); - }); - RowData[k] = newRow; - } - } - - if (_dd[k].component === "AutoSuggest" && _dd[k].isPointer) { - if (RowData[k]) { - let pointer = { - __type: "Pointer", - className: _dd[k].class, - objectId: RowData[k] - }; - RowData[k] = pointer; - } - } - if (_dd[k].format === "date") { - let newdate = new Date(RowData[k]); - RowData[k] = newdate; - } - if (_dd[k].component === "HtmlEditor") { - if (RowData[k]) { - let newHtml = RowData[k] - .replace(/<p[^>]*>/g, "") - .replace(/<\/p>/g, " "); - RowData[k] = newHtml; - } - } - if (_dd[k].component === "DateTime") { - let newDate11; - if (!RowData[k]) { - newDate11 = new Date(); - } else { - newDate11 = new Date(RowData[k]); - } - RowData[k] = newDate11; - } - if (_dd[k].component === "CurrencyInput") { - if (_dd[k].currencyColumn) { - RowData[`${_dd[k].currencyColumn}`] = _dd[k].defaultcurrency; - } - } - if (_dd[k].data !== undefined) { - if (_dd[k].data.isPointer) { - let pointer = undefined; - if (RowData[k] && RowData[k] !== "Select") { - if (_dd[k].type === "array") { - pointer = []; - RowData[k] && - RowData[k].forEach((a) => { - let _kk = {}; - if (_dd[k].data.savePointerClass) { - _kk = { - __type: "Pointer", - className: _dd[k].data.savePointerClass, - objectId: a - }; - } else { - _kk = { - __type: "Pointer", - className: _dd[k].data.class, - objectId: a - }; - } - - pointer.push(_kk); - }); - } else if (_dd[k].data.class) { - if (_dd[k].data.savePointerClass) { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: _dd[k].data.savePointerClass, - objectId: RowData[k] - }; - } - } else if (RowData[k]) { - pointer = { - __type: "Pointer", - className: _dd[k].data.class, - objectId: RowData[k] - }; - } - } else { - if (RowData[k]) { - pointer = { - __type: "Pointer", - className: localStorage.getItem("extended_class"), - objectId: RowData[k] - }; - } - } - - RowData[k] = pointer; - } - } - if (_dd[k].data.FolderTypeValue) { - if (RowData[k]) { - let obj = { - __type: "Pointer", - className: _dd[k].data.ClassName, - objectId: RowData[k] - }; - RowData[k] = obj; - } - } - } - if (_dd[k].type === "string") { - let d = RowData[k]; - if (typeof d === "string") { - RowData[k] = d.trim(); - } - } - }); } }); - Parse.serverURL = this.state.parseBaseUrl; - Parse.initialize(this.state.parseAppId); - const currentUser = Parse.User.current(); - let _fname = this.state.title; - var forms = Parse.Object.extend(_fname); + setFileUpload(response.url()); + setfileload(false); - var form = new forms(); - - form.set("CreatedBy", Parse.User.createWithoutData(currentUser.id)); - - if (this.state["FormACL"]) { - let ACL = {}; - for (let [key, value] of Object.entries(this.state["FormACL"])) { - if (key === "*") { - ACL[key] = value; - } - if (key === "#currentUser#") { - ACL[Parse.User.current().id] = value; - } else if (key.startsWith("#")) { - let arr = key.split("#"); - let new_arr = arr.filter((x) => x !== ""); - if (new_arr.length === 2) { - let l = RowData[new_arr[0]]; - try { - const Agent = Parse.Object.extend(l.className); - const qu = new Parse.Query(Agent); - qu.equalTo("objectId", l.objectId); - qu.include(new_arr[1]); - await qu.first(); - } catch (err) { - console.error("Error while fetching Agent", err.massage); - } - } - } - if (key.startsWith("role")) { - ACL[key] = value; - } - } - form.setACL(new Parse.ACL(ACL)); + if (response.url()) { + return response.url(); } - - form.save(RowData).then( - (form) => { - let filtered = {}; - if (this.state.redirect_type === "clearData") { - if ( - this.state.persistentFields && - this.state.persistentFields.length - ) { - filtered = Object.keys(RowData) - .filter((key) => this.state.persistentFields.includes(key)) - .reduce((obj, key) => { - obj[key] = RowData[key]; - return obj; - }, {}); - } - } else { - RowData = {}; - } - - this.setState( - { - formData: filtered, - active: true, - loading: false, - toastColor: "#5cb85c", - toastDescription: this.state.successMassage - }, - () => { - let redirect_type = this.state.redirect_type; - let redirect_id = this.state.redirect_id; - var x = document.getElementById("snackbar"); - this.props.removeState(); - this.props.removeLevel2State(); - this.props.removeLevel3State(); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 2000); - if (redirect_type === "Form") { - this.props.navigate(`/form/${redirect_id}`); - } else if (redirect_type === "Report") { - this.props.navigate(`/report/${redirect_id}`); - } else if (redirect_type === "Dashboard") { - this.props.navigate(`/dashboard/${redirect_id}`); - } else if (redirect_type === "Url") { - window.location = redirect_id; - } else if (redirect_type === "Microapp") { - window.localStorage.setItem( - "rowlevel", - JSON.stringify({ ...formData, ...form }) - ); - this.props.navigate(`/asmf/${redirect_id}`); - } - } - ); - }, - (error) => { - this.setState({ - loading: false, - active: true, - toastColor: "#d9534f", - toastDescription: error.message - }); - - var x = document.getElementById("snackbar"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 2000); - } - ); } catch (error) { - this.setState({ - loading: false, - active: true, - toastColor: "#d9534f", - toastDescription: error.message - }); - - var x = document.getElementById("snackbar"); - x.className = "show"; - setTimeout(function () { - x.className = x.className.replace("show", ""); - }, 2000); + setfileload(false); + setpercentage(0); + console.error("Error uploading file:", error); } } }; + const dropboxCancel = async () => {}; + const handleSubmit = async (e) => { + e.preventDefault(); + setIsSubmit(true); + try { + const currentUser = Parse.User.current(); + const object = new Parse.Object(props.Cls); + object.set("Name", formData?.Name); + object.set("Description", formData?.Description); + object.set("Note", formData?.Note); + if (props.title === "Request Signature") { + object.set( + "TimeToCompleteDays", + parseInt(formData?.TimeToCompleteDays) + ); + } + object.set("URL", fileupload); + object.set("CreatedBy", Parse.User.createWithoutData(currentUser.id)); + if (folder && folder.ObjectId) { + object.set("Folder", { + __type: "Pointer", + className: props.Cls, + objectId: folder.ObjectId + }); + } + if (signers && signers.length > 0) { + object.set("Signers", signers); + } + const ExtCls = JSON.parse(localStorage.getItem("Extand_Class")); + object.set("ExtUserPtr", { + __type: "Pointer", + className: "contracts_Users", + objectId: ExtCls[0].objectId + }); - saveUrlParamToFormdata = () => { - let url = window.location.hash; - let paramString = url.split("?")[1]; - let queryString = new URLSearchParams(paramString); - let obj = {}; - for (const [key, value] of queryString.entries()) { - obj = { ...obj, [key]: value }; + const res = await object.save(); + if (res) { + setSigners([]); + setFolder({ ObjectId: "", Name: "" }); + setFormData({ + Name: "", + Description: "", + Note: "" + }); + setFileUpload([]); + setpercentage(0); + navigate( + `/asmf/remoteUrl=aHR0cHM6Ly9xaWstYWktb3JnLmdpdGh1Yi5pby9TaWduLU1pY3JvYXBwVjIvcmVtb3RlRW50cnkuanM=&moduleToLoad=AppRoutes&remoteName=signmicroapp/${props?.redirectRoute}/${res.id}` + ); + } + } catch (err) { + console.log("err ", err); + setIsErr(true); + } finally { + setIsAlert(true); + setTimeout(() => { + setIsAlert(false); + }, 1000); + setIsSubmit(false); } - this.setState({ formData: obj }); }; - componentDidMount() { - let url = window.location.hash; - if (url.includes("_app")) { - this.setState({ isAppRequest: true }); + const handleFolder = (data) => { + setFolder(data); + }; + const handleSigners = (data) => { + if (data && data.length > 0) { + const updateSigners = data.map((x) => ({ + __type: "Pointer", + className: "contracts_Contactbook", + objectId: x + })); + setSigners(updateSigners); } - let id = this.props.id; - this.getForm(id); - this.saveUrlParamToFormdata(); - } + }; - UNSAFE_componentWillReceiveProps(newProps) { - let id = newProps.id; - this.getForm(id); - } - - render() { - if (localStorage.getItem("accesstoken") === null) { - this.props.navigate(`/`); - } - - let schema = this.state.schemaState; - let uiSchema = this.state.ui_schema; - let rules = this.state.rules; - let extraActions = this.state.extraActions; - - let FormToDisplay = applyRules( - schema, - uiSchema, - rules, - Engine, - extraActions - )(Form); - let formView = ( - <React.Fragment> - <FormToDisplay - validate={this.state.noValidate && this.dynamicValidate} - showErrorList={false} - widgets={widget} - fields={fields()} - formData={this.state.formData} - liveValidate={this.state.liveValidate} - onSubmit={this.handleSubmit} - validator={validator} - > - <div> - {this.state.active && this.state.buttons.submitText ? ( - <button className="btn btn-info submiBtn" type="submit"> - {this.state.buttons.submitText} - </button> - ) : ( - this.state.buttons.submitText && ( - <button className="btn submiBtn" type="submit" disabled> - {this.state.buttons.submitText} - </button> - ) - )} -    - {this.state.buttons.resetText && ( - <button - className="btn resetBtn" - onClick={(e) => { - e.preventDefault(); - this.setState({ - loading: true, - formData: {} - }); - setTimeout(() => { - this.setState({ loading: false }); - }, 1000); - }} - type="button" - > - {this.state.buttons.resetText} - </button> - )} - </div> - </FormToDisplay> - </React.Fragment> - ); - - if (this.state.loading) { - formView = ( + const handleReset = () => { + setSigners([]); + setFolder({ ObjectId: "", Name: "" }); + setFormData({ + Name: "", + Description: "", + Note: "" + }); + setFileUpload([]); + setpercentage(0); + }; + return ( + <div className="shadow-md rounded my-2 p-3 bg-[#ffffff] md:border-[1px] md:border-gray-600/50"> + <Title title={props?.title} /> + {isAlert && ( + <Alert type={isErr ? "danger" : "success"}> + {isErr + ? "Something went wrong please try again!" + : `${props.msgVar} created successfully!`} + </Alert> + )} + {isSubmit ? ( <div style={{ height: "300px" }}> <div style={{ @@ -1250,85 +249,136 @@ class FormBuilder extends Component { className="loader-37" ></div> </div> - ); - } - return ( - <React.Fragment> - <Title - title={ - this.state.schemaState.title ? this.state.schemaState.title : "" - } - /> - <ErrorBoundary> - <div className="row"> - <div className="col-md-12"> - <div className="card"> - <div className="card-body no-padding height-9"> - {this.state.help ? ( - <div className="dropdown" style={{ marginTop: "-30px" }}> - <i - className="far fa-question-circle dropdown-toggle hovereffect" - aria-hidden="true" - id="dropdownMenuButton" - data-toggle="dropdown" - aria-haspopup="true" - aria-expanded="false" - style={{ - fontSize: "18px", - color: "purple", - cursor: "pointer !important", - position: "relative", - top: "40px", - left: "98%" - }} - ></i> - <div - className="dropdown-menu" - aria-labelledby="dropdownMenuButton" - style={{ - marginleft: "-121px", - margintop: "-14px", - position: "absolute", - padding: "10px", - width: "300px", - top: "102px!important" - }} - > - {parse(` - ${this.state.help} - `)} - <br /> - {this.state.link ? ( - <a - onClick={(e) => { - e.preventDefault(); - window.location.href = this.state.link; - }} - target="_blank" - className="btn btn-xs btn-primary" - > - Read more.. - </a> - ) : null} - </div> - </div> - ) : null} - <div style={{ fontSize: "13px" }}>{formView}</div> - </div> + ) : ( + <form onSubmit={handleSubmit}> + <h1 className="text-[20px] font-semibold mb-4">{props?.title}</h1> + {fileload && ( + <div className="flex items-center gap-x-2"> + <div className="h-2 rounded-full w-[200px] md:w-[400px] bg-gray-200"> + <div + className="h-2 rounded-full bg-blue-500" + style={{ width: `${percentage}%` }} + ></div> </div> + <span className="text-black text-sm">{percentage}%</span> + </div> + )} + <div className="text-xs"> + <label className="block"> + File<span className="text-red-500 text-[13px]">*</span> + </label> + {fileupload.length > 0 ? ( + <div className="flex gap-2 justify-center items-center"> + <div className="flex justify-between items-center px-2 py-2 w-full font-bold rounded border-[1px] border-[#ccc] text-gray-500 bg-white text-[13px]"> + <div className="break-all"> + file selected : {fileupload?.split("/")[3]?.split("_")[1]} + </div> + <div + onClick={() => { + setFileUpload([]); + }} + className="cursor-pointer px-[10px] text-[20px] font-bold bg-white text-red-500" + > + <i className="fa-solid fa-xmark"></i> + </div> + </div> + {process.env.REACT_APP_DROPBOX_API_KEY && ( + <DropboxChooser + onSuccess={dropboxSuccess} + onCancel={dropboxCancel} + /> + )} + </div> + ) : ( + <div className="flex gap-2 justify-center items-center"> + <input + type="file" + className="bg-white px-2 py-1.5 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + onChange={(e) => handleFileInput(e)} + accept="application/pdf" + required + /> + {process.env.REACT_APP_DROPBOX_API_KEY && ( + <DropboxChooser + onSuccess={dropboxSuccess} + onCancel={dropboxCancel} + /> + )} + </div> + )} + </div> + <div className="text-xs mt-2"> + <label className="block"> + Title<span className="text-red-500 text-[13px]">*</span> + </label> + <input + name="Name" + className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + value={formData.Name} + onChange={(e) => handleStrInput(e)} + required + /> + </div> + <div className="text-xs mt-2"> + <label className="block">Description</label> + <input + name="Description" + className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + value={formData.Description} + onChange={(e) => handleStrInput(e)} + /> + </div> + {props.signers && <SignersInput onChange={handleSigners} required />} + <div className="text-xs mt-2"> + <label className="block"> + Note<span className="text-red-500 text-[13px]">*</span> + </label> + <input + name="Note" + className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + value={formData.Note} + onChange={(e) => handleStrInput(e)} + required + /> + </div> + <SelectFolder onSuccess={handleFolder} folderCls={props.Cls} /> + + {props.title === "Request Signature" && ( + <div className="text-xs mt-2"> + <label className="block"> + Time To Complete (Days) + <span className="text-red-500 text-[13px]">*</span> + </label> + <input + type="number" + name="TimeToCompleteDays" + className="px-3 py-2 w-full border-[1px] border-gray-300 rounded focus:outline-none text-xs" + value={formData.TimeToCompleteDays} + onChange={(e) => handleStrInput(e)} + required + /> + </div> + )} + <div className="flex items-center mt-3 gap-2 text-white"> + <button + className={`${ + isSubmit && "cursor-progress" + } bg-[#1ab6ce] rounded-sm shadow-md text-[13px] font-semibold uppercase text-white py-1.5 px-2.5 focus:outline-none`} + type="submit" + disabled={isSubmit} + > + Submit + </button> + <div + className="bg-[#188ae2] rounded-sm shadow-md text-[13px] font-semibold uppercase text-white py-1.5 px-2.5 text-center ml-[2px] focus:outline-none" + onClick={() => handleReset()} + > + Reset </div> </div> - <div id="snackbar" style={{ backgroundColor: this.state.toastColor }}> - {this.state.toastDescription} - </div> - </ErrorBoundary> - </React.Fragment> - ); - } -} - -export default connect(null, { - removeState, - removeLevel2State, - removeLevel3State -})(FormBuilderFn); + </form> + )} + </div> + ); +}; +export default Form; diff --git a/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js b/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js index 2e50b25a8..671b91d9d 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js +++ b/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js @@ -1,9 +1,13 @@ async function getUserDetails(request) { try { + const userId = request.params.userId; const userQuery = new Parse.Query('contracts_Users'); userQuery.equalTo('Email', request.params.email); userQuery.include('TenantId'); - userQuery.include('UserId') + userQuery.include('UserId'); + if (userId) { + userQuery.equalTo('CreatedBy', { __type: 'Pointer', className: '_User', objectId: userId }); + } const res = await userQuery.first({ useMasterKey: true }); return res; } catch (err) {