fix: duplicate entries in ancestors array and login issue

This commit is contained in:
prafull-opensignlabs
2024-07-02 00:27:29 +05:30
parent d46ba8f307
commit abd7cf9b71
7 changed files with 265 additions and 212 deletions
+5 -12
View File
@@ -49,18 +49,11 @@ const AddDepartment = (props) => {
(x) => x.objectId === formdata.department
)?.Ancestors;
if (Ancestors && Ancestors.length > 0) {
updatedAncestors = [
...Ancestors.map((x) => ({
__type: "Pointer",
className: "contracts_Departments",
objectId: x.objectId
})),
{
__type: "Pointer",
className: "contracts_Departments",
objectId: formdata.department
}
];
updatedAncestors = Ancestors.map((x) => ({
__type: "Pointer",
className: "contracts_Departments",
objectId: x.objectId
}));
} else {
updatedAncestors.push({
__type: "Pointer",
+60 -10
View File
@@ -4,6 +4,19 @@ import axios from "axios";
import Title from "./Title";
import Alert from "../primitives/Alert";
import Loader from "../primitives/Loader";
import { copytoData } from "../constant/Utils";
function generatePassword(length) {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
const AddUser = (props) => {
const [formdata, setFormdata] = useState({
@@ -11,12 +24,13 @@ const AddUser = (props) => {
phone: "",
email: "",
department: "",
password: "",
role: ""
});
const [isLoader, setIsLoader] = useState(false);
const [isUserExist, setIsUserExist] = useState(false);
const [isAlert, setIsAlert] = useState({ type: "success", msg: "" });
const [departmentList, setDepartmentList] = useState([]);
const role = ["OrgAdmin", "Manager", "User", "Guest"];
const role = ["OrgAdmin", "Manager", "User"];
const parseBaseUrl = localStorage.getItem("baseUrl");
const parseAppId = localStorage.getItem("parseAppId");
@@ -25,6 +39,7 @@ const AddUser = (props) => {
}, []);
const getDepartmentList = async () => {
setFormdata((prev) => ({ ...prev, password: generatePassword(12) }));
const extUser = JSON.parse(localStorage.getItem("Extand_Class"))?.[0];
const department = new Parse.Query("contracts_Departments");
department.equalTo("OrganizationId", {
@@ -59,14 +74,14 @@ const AddUser = (props) => {
e.preventDefault();
e.stopPropagation();
const localUser = JSON.parse(localStorage.getItem("Extand_Class"))?.[0];
console.log("formdata.department ", formdata.department);
setIsLoader(true);
const res = await checkUserExist();
if (res) {
setIsUserExist(true);
setIsAlert({ type: "danger", msg: "User already exist." });
setIsLoader(false);
setTimeout(() => {
setIsUserExist(false);
setIsAlert({ type: "success", msg: "" });
}, 1000);
} else {
try {
@@ -106,7 +121,7 @@ const AddUser = (props) => {
_user.set("name", formdata.name);
_user.set("username", formdata.email);
_user.set("email", formdata.email);
_user.set("password", formdata.email);
_user.set("password", formdata.password);
if (formdata.phone) {
_user.set("phone", formdata.phone);
}
@@ -218,7 +233,9 @@ const AddUser = (props) => {
} catch (err) {
console.log("err", err);
setIsLoader(false);
alert("something went wrong!");
setIsAlert({ type: "danger", msg: "something went wrong." });
} finally {
setTimeout(() => setIsAlert({ type: "success", msg: "" }), 1500);
}
}
};
@@ -232,15 +249,30 @@ const AddUser = (props) => {
department: "",
role: ""
});
if (props.closePopup) {
props.closePopup();
}
};
const handleChange = (e) => {
console.log("e", e.target.name, e.target.value);
setFormdata((prev) => ({ ...prev, [e.target.name]: e.target.value }));
};
const copytoclipboard = (text) => {
copytoData(text);
setIsAlert({ type: "success", msg: "Copied" });
setTimeout(() => {
setIsAlert({ type: "success", msg: "" });
}, 1500); // Reset copied state after 1.5 seconds
};
return (
<div className="shadow-md rounded-box my-[1px] p-3 bg-[#ffffff]">
<Title title={"Add User"} />
{isUserExist && <Alert type="danger">User already exists!</Alert>}
{isAlert.msg && (
<Alert type={isAlert.type}>
<div className="ml-3">{isAlert.msg}</div>
</Alert>
)}
{isLoader && (
<div className="fixed inset-0 flex justify-center items-center bg-black bg-opacity-30 z-50 rounded-box">
<Loader />
@@ -283,6 +315,24 @@ const AddUser = (props) => {
className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full text-xs"
/>
</div>
<div className="mb-3">
<label
htmlFor="email"
className="block text-xs text-gray-700 font-semibold"
>
Password
</label>
<div className="flex justify-between items-center op-input op-input-bordered op-input-sm bg-base-200 text-base-content w-full h-full text-[13px]">
<div className="break-all">{formdata?.password}</div>
<i
onClick={() => copytoclipboard(formdata?.password)}
className="fa-light fa-copy rounded-full hover:bg-base-300 p-[8px]"
></i>
</div>
<div className="text-[12px] ml-2 mb-0 text-[red]">
Password will be generated one time; make sure to copy it.
</div>
</div>
<div className="mb-3">
<label
htmlFor="phone"
@@ -315,7 +365,7 @@ const AddUser = (props) => {
className="op-select op-select-bordered op-select-sm focus:outline-none hover:border-base-content w-full text-xs"
required
>
<option disabled>select</option>
<option>select</option>
{departmentList.length > 0 &&
departmentList.map((x) => (
<option key={x.objectId} value={x.objectId}>
@@ -356,7 +406,7 @@ const AddUser = (props) => {
onClick={() => handleReset()}
className="op-btn op-btn-secondary"
>
Reset
Cancel
</div>
</div>
</form>
+17 -3
View File
@@ -21,15 +21,29 @@ export const appInfo = {
objectId: "aIPmIvMzGM",
settings: [
{
role: "contracts_User",
role: "contracts_Admin",
menuId: "VPh91h0ZHk",
pageType: "dashboard",
pageId: "35KBoSgoAK",
extended_class: "contracts_Users"
},
{
role: "contracts_OrgAdmin",
menuId: "VPh91h0ZHk",
pageType: "dashboard",
pageId: "35KBoSgoAK",
extended_class: "contracts_Users"
},
{
role: "contracts_Manager",
menuId: "H9vRfEYKhT",
pageType: "dashboard",
pageId: "35KBoSgoAK",
extended_class: "contracts_Users"
},
{
role: "contracts_Admin",
menuId: "VPh91h0ZHk",
role: "contracts_User",
menuId: "H9vRfEYKhT",
pageType: "dashboard",
pageId: "35KBoSgoAK",
extended_class: "contracts_Users"
+2 -2
View File
@@ -8,7 +8,7 @@ import ModalUi from "../primitives/ModalUi";
import pad from "../assets/images/pad.svg";
import AddDepartment from "../components/AddDepartment";
const heading = ["Sr.No", "Name", "Parent Department", "IsActive"];
const heading = ["Sr.No", "Name", "Parent Department", "Is-Active"];
// const actions = [
// {
// btnId: "1231",
@@ -185,7 +185,7 @@ const DepartmentList = () => {
<div className="p-2 w-full bg-base-100 text-base-content op-card shadow-lg">
{isAlert.msg && (
<Alert type={isAlert.type}>
<div className="ml-3">{isAlert.message}</div>
<div className="ml-3">{isAlert.msg}</div>
</Alert>
)}
<div className="flex flex-row items-center justify-between my-2 mx-3 text-[20px] md:text-[23px]">
+2 -2
View File
@@ -645,8 +645,8 @@ const Forms = (props) => {
</label>
{fileupload.length > 0 ? (
<div className="flex gap-2 justify-center items-center">
<div className="flex justify-between items-center op-input op-input-bordered op-input-sm w-full h-full text-x text-[13px]">
<div className="break-all ">
<div className="flex justify-between items-center op-input op-input-bordered op-input-sm w-full h-full text-[13px]">
<div className="break-all">
file selected: {getFileName(fileupload)}
</div>
<div
+176 -180
View File
@@ -693,182 +693,124 @@ function Login() {
setState({ ...state, loading: true });
try {
const user = await Parse.User.become(localStorage.getItem("accesstoken"));
let _usss = user.toJSON();
localStorage.setItem("UserInformation", JSON.stringify(_usss));
localStorage.setItem("username", _usss.name);
localStorage.setItem("accesstoken", _usss.sessionToken);
let _user = user.toJSON();
localStorage.setItem("UserInformation", JSON.stringify(_user));
localStorage.setItem("username", _user.name);
localStorage.setItem("accesstoken", _user.sessionToken);
localStorage.setItem("scriptId", true);
if (_usss.ProfilePic) {
localStorage.setItem("profileImg", _usss.ProfilePic);
if (_user.ProfilePic) {
localStorage.setItem("profileImg", _user.ProfilePic);
} else {
localStorage.setItem("profileImg", "");
}
let userRoles = [];
let userSettings = appInfo.settings;
if (localStorage.getItem("userSettings")) {
let userSettings = localStorage.getItem("userSettings");
//Get Current user roles
let url = `${localStorage.getItem("baseUrl")}functions/UserGroups`;
const headers1 = {
"Content-Type": "application/json",
"X-Parse-Application-Id": localStorage.getItem("parseAppId"),
sessionToken: _user.sessionToken
};
const body = { appname: "contracts" };
//Get Current user roles
let url = `${localStorage.getItem("baseUrl")}functions/UserGroups`;
const headers1 = {
"Content-Type": "application/json",
"X-Parse-Application-Id": localStorage.getItem("parseAppId"),
sessionToken: _usss.sessionToken
};
let body = {
appname: localStorage.getItem("_appName")
};
await axios
.post(url, JSON.stringify(body), { headers: headers1 })
.then((axiosres) => {
const roles = axiosres.data.result;
if (roles) {
userRoles = roles;
let _currentRole = "";
if (userRoles.length > 1) {
if (userRoles[0] === "contracts_appeditor") {
_currentRole = userRoles[1];
} else {
const rolesfiltered = userRoles.filter(
(x) => x !== "contracts_Guest"
await axios
.post(url, JSON.stringify(body), { headers: headers1 })
.then((axiosres) => {
const roles = axiosres.data.result;
console.log("roles ", roles);
if (roles && roles.length > 0) {
userRoles = roles;
let _currentRole = "";
const valuesToExclude = ["contracts_Guest", "contracts_appeditor"];
const filterRoles = userRoles.filter(
(x) => !valuesToExclude.includes(x)
);
if (filterRoles.length > 0) {
_currentRole = filterRoles?.[0];
console.log("_currentRole ", _currentRole);
let SettingsUser = userSettings;
SettingsUser.forEach(async (item) => {
if (item.role === _currentRole) {
let _role = _currentRole.replace(`${appInfo.appname}_`, "");
localStorage.setItem("_user_role", _role);
// Get TenentID from Extendend Class
localStorage.setItem("extended_class", item.extended_class);
const currentUser = Parse.User.current();
const userSettings = appInfo.settings;
const setting = userSettings.find(
(x) => x.role === _currentRole
);
if (rolesfiltered.length > 0) {
_currentRole = rolesfiltered[0];
} else {
setThirdpartyLoader(false);
setState({
...state,
loading: false,
alertType: "danger",
alertMsg:
"Does not have permissions to access this application!"
});
setTimeout(function () {
setState({
...state,
loading: false,
alertType: "danger",
alertMsg: ""
});
}, 2000);
}
// _currentRole = userRoles[0];
}
} else {
_currentRole = userRoles[0];
}
if (_currentRole && _currentRole !== "contracts_Guest") {
let SettingsUser = JSON.parse(userSettings);
SettingsUser.forEach(async (item) => {
if (item.role === _currentRole) {
let _role = _currentRole.replace(`${appInfo.appname}_`, "");
localStorage.setItem("_user_role", _role);
// Get TenentID from Extendend Class
localStorage.setItem("extended_class", item.extended_class);
const currentUser = Parse.User.current();
const userSettings = appInfo.settings;
const setting = userSettings.find(
(x) => x.role === _currentRole
);
const redirectUrl =
location?.state?.from ||
`/${setting.pageType}/${setting.pageId}`;
await Parse.Cloud.run("getUserDetails", {
email: currentUser.get("email")
}).then(
async (result) => {
let tenentInfo = [];
const results = [result];
if (results) {
let extendedInfo_stringify = JSON.stringify(results);
let extendedInfo = JSON.parse(extendedInfo_stringify);
if (extendedInfo.length > 1) {
extendedInfo.forEach((x) => {
if (x.TenantId) {
let obj = {
tenentId: x.TenantId.objectId,
tenentName: x.TenantId.TenantName || ""
};
tenentInfo.push(obj);
}
});
localStorage.setItem("showpopup", true);
localStorage.setItem("PageLanding", item.pageId);
localStorage.setItem("defaultmenuid", item.menuId);
localStorage.setItem("pageType", item.pageType);
navigate("/");
} else {
extendedInfo.forEach((x) => {
if (x.TenantId) {
let obj = {
tenentId: x.TenantId.objectId,
tenentName: x.TenantId.TenantName || ""
};
localStorage.setItem(
"TenantId",
x.TenantId.objectId
);
tenentInfo.push(obj);
}
});
localStorage.setItem("PageLanding", setting.pageId);
localStorage.setItem(
"defaultmenuid",
setting.menuId
);
localStorage.setItem("pageType", setting.pageType);
if (isEnableSubscription) {
const LocalUserDetails = {
name: results[0].get("Name"),
email: results[0].get("Email"),
phone: results[0]?.get("Phone") || "",
company: results[0].get("Company")
const redirectUrl =
location?.state?.from ||
`/${setting.pageType}/${setting.pageId}`;
await Parse.Cloud.run("getUserDetails", {
email: currentUser.get("email")
}).then(
async (result) => {
let tenentInfo = [];
const results = [result];
if (results) {
let extendedInfo_stringify = JSON.stringify(results);
let extendedInfo = JSON.parse(extendedInfo_stringify);
if (extendedInfo.length > 1) {
extendedInfo.forEach((x) => {
if (x.TenantId) {
let obj = {
tenentId: x.TenantId.objectId,
tenentName: x.TenantId.TenantName || ""
};
tenentInfo.push(obj);
}
});
localStorage.setItem("showpopup", true);
localStorage.setItem("PageLanding", item.pageId);
localStorage.setItem("defaultmenuid", item.menuId);
localStorage.setItem("pageType", item.pageType);
navigate("/");
} else {
extendedInfo.forEach((x) => {
if (x.TenantId) {
let obj = {
tenentId: x.TenantId.objectId,
tenentName: x.TenantId.TenantName || ""
};
localStorage.setItem(
"userDetails",
JSON.stringify(LocalUserDetails)
"TenantId",
x.TenantId.objectId
);
const res = await fetchSubscription();
const billingDate = res.billingDate;
const freeplan = res.plan;
if (freeplan === "freeplan") {
navigate(redirectUrl);
} else if (billingDate) {
if (new Date(billingDate) > new Date()) {
localStorage.removeItem("userDetails");
// Redirect to the appropriate URL after successful login
navigate(redirectUrl);
} else {
navigate(`/subscription`);
}
} else {
navigate(`/subscription`);
}
} else {
// Redirect to the appropriate URL after successful login
navigate(redirectUrl);
tenentInfo.push(obj);
}
}
} else {
});
localStorage.setItem("PageLanding", setting.pageId);
localStorage.setItem("defaultmenuid", setting.menuId);
localStorage.setItem("pageType", setting.pageType);
setState({ ...state, loading: false });
if (isEnableSubscription) {
const LocalUserDetails = {
name: results[0].get("Name"),
email: results[0].get("Email"),
phone: results[0]?.get("Phone") || ""
// company: results.get("Company"),
phone: results[0]?.get("Phone") || "",
company: results[0].get("Company")
};
localStorage.setItem(
"userDetails",
JSON.stringify(LocalUserDetails)
);
const billingDate = "";
if (billingDate) {
const res = await fetchSubscription();
const billingDate = res.billingDate;
const freeplan = res.plan;
if (freeplan === "freeplan") {
navigate(redirectUrl);
} else if (billingDate) {
if (new Date(billingDate) > new Date()) {
localStorage.removeItem("userDetails");
// Redirect to the appropriate URL after successful login
navigate(redirectUrl);
} else {
navigate(`/subscription`);
}
} else {
navigate(`/subscription`);
}
} else {
@@ -876,41 +818,95 @@ function Login() {
navigate(redirectUrl);
}
}
},
(error) => {
} else {
localStorage.setItem("PageLanding", setting.pageId);
localStorage.setItem("defaultmenuid", setting.menuId);
localStorage.setItem("pageType", setting.pageType);
setState({ ...state, loading: false });
if (isEnableSubscription) {
const LocalUserDetails = {
name: results[0].get("Name"),
email: results[0].get("Email"),
phone: results[0]?.get("Phone") || ""
// company: results.get("Company"),
};
localStorage.setItem(
"userDetails",
JSON.stringify(LocalUserDetails)
);
const billingDate = "";
if (billingDate) {
navigate(`/subscription`);
}
} else {
// Redirect to the appropriate URL after successful login
navigate(redirectUrl);
}
}
},
(error) => {
setState({
...state,
loading: false,
alertType: "danger",
alertMsg: "You don`t have access to this application!"
});
setTimeout(function () {
setState({
...state,
loading: false,
alertType: "danger",
alertMsg: "You don`t have access to this application!"
alertMsg: ""
});
setTimeout(function () {
setState({
...state,
loading: false,
alertType: "danger",
alertMsg: ""
});
}, 2000);
localStorage.setItem("accesstoken", null);
console.error("Error while fetching Follow", error);
}
);
}
});
} else {
setState({ ...state, loading: false });
handleCloseModal();
}
}, 2000);
localStorage.setItem("accesstoken", null);
console.error("Error while fetching Follow", error);
}
);
}
});
} else {
console.log("User Role Not Found.");
setState({ ...state, loading: false });
handleCloseModal();
setThirdpartyLoader(false);
setState({
...state,
loading: false,
alertType: "danger",
alertMsg:
"Does not have permissions to access this application!"
});
setTimeout(function () {
setState({
...state,
loading: false,
alertType: "danger",
alertMsg: ""
});
}, 2000);
}
})
.catch((err) => {
setState({ ...state, loading: false });
console.log("err", err);
});
}
} else {
console.log("User Role Not Found.");
setThirdpartyLoader(false);
setState({
...state,
loading: false,
alertType: "danger",
alertMsg: "Does not have permissions to access this application!"
});
setTimeout(function () {
setState({
...state,
alertType: "danger",
alertMsg: ""
});
}, 2000);
}
})
.catch((err) => {
setState({ ...state, loading: false });
console.log("err", err);
});
} catch (error) {
setState({ ...state, loading: false });
console.log("err", error);
+3 -3
View File
@@ -13,8 +13,8 @@ const heading = [
"Email",
"Phone",
"Role",
"Departments",
"IsActive"
"Department",
"Is-Active"
];
// const actions = [];
const UserList = () => {
@@ -182,7 +182,7 @@ const UserList = () => {
<div className="p-2 w-full bg-base-100 text-base-content op-card shadow-lg">
{isAlert.msg && (
<Alert type={isAlert.type}>
<div className="ml-3">{isAlert.message}</div>
<div className="ml-3">{isAlert.msg}</div>
</Alert>
)}
<div className="flex flex-row items-center justify-between my-2 mx-3 text-[20px] md:text-[23px]">