Compare commits
30 Commits
Yasin
...
Sprint-9.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 4d6a8bb472 | |||
|
|
41a60c0892 | ||
|
|
5c05a68bb0 | ||
| f02f9c8b7d | |||
|
|
137912aa11 | ||
| e3fe5a1618 | |||
|
|
edcb4cd7b9 | ||
| c72f3ece4e | |||
|
|
85be7c891e | ||
|
|
e41d6b17b9 | ||
| 3217605a0f | |||
| b4d28387fa | |||
|
|
5411d4cd18 | ||
|
|
6a0aa17e2d | ||
|
|
471e4f32ab | ||
|
|
5d2c28f6ca | ||
|
|
49f39e1c2c | ||
|
|
f9c7bf9d5d | ||
|
|
49beb9539a | ||
|
|
ed27ed6939 | ||
|
|
d84b3a0e35 | ||
|
|
20c0c7840f | ||
|
|
bbfd617b27 | ||
|
|
87e0716383 | ||
|
|
c7d6a0fe36 | ||
|
|
c83aaa411a | ||
|
|
a2fe1435cb | ||
| 6a9e0f9908 | |||
|
|
4ca28fd910 | ||
| 88dc9d14fe |
28
.env.example
Normal file
28
.env.example
Normal file
@@ -0,0 +1,28 @@
|
||||
# Default Value Maker
|
||||
VITE_MAKER="Maker"
|
||||
|
||||
# Default Value Checker
|
||||
VITE_CHECKER="Checker"
|
||||
|
||||
# Role Encryption key
|
||||
VITE_ROLE_ENCRYPTION_KEY="export"
|
||||
|
||||
# Super Admin
|
||||
VITE_SUPER_ADMIN_ID=1
|
||||
|
||||
# BaseURL
|
||||
VITE_BAS_URL="your_base_url"
|
||||
|
||||
# BaseURL for Images
|
||||
VITE_IMAGE_URL="your_base_url"
|
||||
|
||||
# Max try re-genrate token
|
||||
VITE_MAX_TRY_REGENRATE_TOKEN=3
|
||||
|
||||
VITE_STATUS_DRAFT="Draft"
|
||||
VITE_STATUS_PROCESSING="Processing"
|
||||
VITE_STATUS_OPEN="Open"
|
||||
VITE_STATUS_CLOSED="Closed"
|
||||
VITE_STATUS_EXITED="Exited"
|
||||
VITE_STATUS_CANCELLED="Cancelled"
|
||||
VITE_STATUS_DEACTIVATE="DeActivate"
|
||||
117
README.md
117
README.md
@@ -1,10 +1,113 @@
|
||||
# React + Vite
|
||||
# **Tanami Capital**
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
**Tanami** is a cutting-edge fintech platform designed to streamline investment opportunities for users in the Gulf region. It features two main components:
|
||||
|
||||
Currently, two official plugins are available:
|
||||
- **Admin Panel:** A web-based dashboard for managing users, monitoring transactions, and overseeing investments efficiently.
|
||||
- **Mobile Application:** A user-friendly app that empowers individuals to invest in diverse asset classes, including real estate, private equity, and other financial instruments located in Gulf countries.
|
||||
|
||||
---
|
||||
|
||||
## **Key Features**
|
||||
- **Regional Focus:** Exclusively operational in Gulf countries, offering investment opportunities tailored to the region.
|
||||
- **Diverse Investment Options:** Enables users to invest in financial instruments like real estate and private equity with ease and transparency.
|
||||
- **Comprehensive Admin Tools:** The admin panel offers robust tools for tracking and managing platform activity.
|
||||
|
||||
---
|
||||
|
||||
## **Current Status**
|
||||
The project is **live and operational**, catering specifically to the investment needs of users in the Gulf region.
|
||||
|
||||
---
|
||||
|
||||
## **Table of Contents**
|
||||
- [Installation](#installation)
|
||||
- [Usage](#usage)
|
||||
- [Environment Variables](#environment-variables)
|
||||
- [Scripts](#scripts)
|
||||
- [License](#license)
|
||||
|
||||
---
|
||||
|
||||
## **Installation**
|
||||
|
||||
### **Prerequisites**
|
||||
- [Node.js](https://nodejs.org/) (version 14 or higher recommended)
|
||||
- [npm](https://www.npmjs.com/) (bundled with Node.js)
|
||||
|
||||
### **Steps**
|
||||
1. Clone the repository:
|
||||
```bash
|
||||
git clone http://git.wdipl.com/Siddhesh.More/tanami-admin-panel.git
|
||||
```
|
||||
2. Navigate to the project directory:
|
||||
```bash
|
||||
cd tanami-admin-panel
|
||||
```
|
||||
3. Install dependencies:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## **Usage**
|
||||
|
||||
### **Development Mode**
|
||||
1. Start the development server:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
2. Open your browser and navigate to:
|
||||
```
|
||||
http://localhost:5173/
|
||||
```
|
||||
|
||||
### **Production Mode**
|
||||
1. Install [PM2](https://pm2.keymetrics.io/) globally for process management:
|
||||
```bash
|
||||
npm install pm2 -g
|
||||
```
|
||||
|
||||
2. Build the application (if applicable):
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
3. Serve the application using PM2:
|
||||
```bash
|
||||
pm2 serve ./dist <port_number> --spa --name=<application_name>
|
||||
```
|
||||
Replace:
|
||||
- `./dist` with your build directory.
|
||||
- `<port_number>` with the desired port (e.g., `3000`).
|
||||
- `<application_name>` with the name of your application.
|
||||
|
||||
4. Save the PM2 process list and enable startup on system reboot:
|
||||
```bash
|
||||
pm2 save
|
||||
pm2 startup
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## **Environment Variables**
|
||||
|
||||
Create a `.env` file in the root directory based on the structure of [`.env.example`](.env.example).
|
||||
|
||||
---
|
||||
|
||||
## **Scripts**
|
||||
|
||||
| Script | Description |
|
||||
|---------------------|-------------------------------------------------------------|
|
||||
| `npm run dev` | Starts the app in development mode with `Vite` server. |
|
||||
| `npm run build` | Builds the app for production. |
|
||||
| `npm run lint` | Runs ESLint to check for code quality issues. |
|
||||
| `npm run preview` | Previews the production build locally. |
|
||||
|
||||
---
|
||||
|
||||
## **License**
|
||||
|
||||
This project is licensed under the [MIT License](LICENSE).
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
# rubix-admin-panel
|
||||
# tanami-admin-panel
|
||||
|
||||
@@ -63,8 +63,8 @@ const App = () => {
|
||||
path="/*"
|
||||
element={
|
||||
// isOnline ? (
|
||||
// isAuthenticate || isAuthenticatedInCookie === "true" ? (
|
||||
localStorage.getItem('accessToken') && localStorage.getItem('refreshToken') ? (
|
||||
isAuthenticate || isAuthenticatedInCookie === "true" ? (
|
||||
// localStorage.getItem('accessToken') && localStorage.getItem('refreshToken') ? (
|
||||
// true ? (
|
||||
<DefaultLayout isOnline={isOnline} />
|
||||
) : (
|
||||
|
||||
@@ -5,7 +5,7 @@ import { ChevronLeftIcon, ChevronRightIcon } from "@chakra-ui/icons";
|
||||
const Pagination = ({
|
||||
pageSize,
|
||||
setPageSize,
|
||||
totalItems,
|
||||
totalItems = 1,
|
||||
isLoading,
|
||||
setCurrentPage,
|
||||
currentPage,
|
||||
@@ -84,7 +84,7 @@ const Pagination = ({
|
||||
onClick={paginationNext}
|
||||
className="link pointer"
|
||||
isDisabled={currentPage === totalPages}
|
||||
aria-label="Next Page"
|
||||
aria-label="Next Page"
|
||||
/>
|
||||
</HStack>
|
||||
</HStack>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Box, Text } from "@chakra-ui/react";
|
||||
import React, { useRef } from "react";
|
||||
import audioClick from "../assets/click-151673.mp3";
|
||||
import React from "react";
|
||||
|
||||
const RoleSwitchButton = ({ isSwitchOn, setIsSwitchOn }) => {
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
|
||||
import dns from "node:dns"
|
||||
import * as XLSX from 'xlsx';
|
||||
import CryptoJS from "crypto-js";
|
||||
|
||||
|
||||
export const generateSerialNumber = (index, currentPage, pageSize) => {
|
||||
export const generateSerialNumber = (index, currentPage = 1, pageSize = 1) => {
|
||||
return (currentPage - 1) * pageSize + (index + 1);
|
||||
};
|
||||
|
||||
@@ -12,7 +11,7 @@ export function getTomorrowDate() {
|
||||
const today = new Date();
|
||||
const tomorrow = new Date(today);
|
||||
tomorrow.setDate(today.getDate() + 1);
|
||||
|
||||
|
||||
// Format the date as YYYY-MM-DD (ISO 8601)
|
||||
return tomorrow.toISOString().split('T')[0];
|
||||
}
|
||||
@@ -34,7 +33,7 @@ export function removeTrailingZeros(value) {
|
||||
}
|
||||
|
||||
|
||||
export function getCountdownTimer(utcDateString) {
|
||||
export function getCountdownTimer(utcDateString) {
|
||||
// Parse the UTC datetime string into a Date object
|
||||
const targetDate = new Date(utcDateString);
|
||||
const now = new Date();
|
||||
@@ -57,7 +56,7 @@ export function removeTrailingZeros(value) {
|
||||
const remainingMinutes = minutes % 60;
|
||||
const remainingSeconds = seconds % 60;
|
||||
|
||||
return `${remainingDays === 0 ? "": remainingDays+"d"} ${remainingHours === 0 ? "": remainingHours+"h"} ${remainingMinutes}m ${remainingSeconds}s `;
|
||||
return `${remainingDays === 0 ? "" : remainingDays + "d"} ${remainingHours === 0 ? "" : remainingHours + "h"} ${remainingMinutes}m ${remainingSeconds}s `;
|
||||
}
|
||||
|
||||
|
||||
@@ -95,30 +94,33 @@ export function debounce(func, delay) {
|
||||
|
||||
|
||||
|
||||
async function resolveMx(domain, recordType) {
|
||||
async function resolveMx(domain) {
|
||||
return new Promise((resolve, reject) => {
|
||||
dns.resolveMx(domain, (err, mxRecords) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
const addresses = mxRecords.map((mxRecord) => mxRecord.exchange);
|
||||
resolve(addresses);
|
||||
});
|
||||
dns.resolveMx(domain, (err, mxRecords) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
const addresses = mxRecords.map((mxRecord) => mxRecord.exchange);
|
||||
resolve(addresses);
|
||||
});
|
||||
});
|
||||
}
|
||||
// Async function to check email address validity
|
||||
export async function checkEmailValidity(email) {
|
||||
try {
|
||||
const domain = email?.split("@")[1];
|
||||
const addresses = await resolveMx(domain, "MX");
|
||||
const domain = email?.split('@')[1];
|
||||
const addresses = await resolveMx(domain, 'MX');
|
||||
console.log(addresses);
|
||||
|
||||
if (addresses && addresses?.length > 0) {
|
||||
return true;
|
||||
}
|
||||
return false; // No MX record exists
|
||||
if (addresses && addresses?.length > 0) {
|
||||
return true;
|
||||
}
|
||||
return false; // No MX record exists
|
||||
} catch (err) {
|
||||
return false; // Error occurred
|
||||
console.log(err);
|
||||
|
||||
return false; // Error occurred
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,15 +128,15 @@ export async function checkEmailValidity(email) {
|
||||
// Function to convert timestamp to readable date format in Gulf timezone
|
||||
export function formatTimestampInGulfTimezone(timestamp) {
|
||||
const date = new Date(timestamp);
|
||||
const options = {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
timeZone: 'Asia/Dubai', // Gulf Standard Time (GST) timezone
|
||||
timeZoneName: 'short'
|
||||
const options = {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
timeZone: 'Asia/Dubai', // Gulf Standard Time (GST) timezone
|
||||
timeZoneName: 'short'
|
||||
};
|
||||
return date.toLocaleDateString('en-GB', options);
|
||||
}
|
||||
@@ -164,7 +166,7 @@ const getNestedValue = (obj, key) => {
|
||||
export const exportToExcel = (data, headers) => {
|
||||
const flattenedData = data.map((item) => {
|
||||
const newItem = {};
|
||||
|
||||
|
||||
// Loop through customHeaders and get the correct values
|
||||
headers.forEach((header) => {
|
||||
newItem[header.label] = getNestedValue(item, header.key); // Use the helper function
|
||||
@@ -175,7 +177,7 @@ export const exportToExcel = (data, headers) => {
|
||||
|
||||
// Now pass flattenedData to your Excel library to generate the file
|
||||
// Assuming you're using a library like `xlsx` for this part:
|
||||
|
||||
|
||||
const worksheet = XLSX.utils.json_to_sheet(flattenedData);
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
|
||||
@@ -233,4 +235,11 @@ export const decryptString = (ciphertext) => {
|
||||
const bytes = CryptoJS.AES.decrypt(ciphertext, import.meta.env.VITE_ROLE_ENCRYPTION_KEY);
|
||||
const originalText = bytes.toString(CryptoJS.enc.Utf8);
|
||||
return originalText;
|
||||
};
|
||||
};
|
||||
|
||||
export const SUPER_ADMIN_ID = Number(import.meta.env.VITE_SUPER_ADMIN_ID) || 1
|
||||
export const MAKER_ID = import.meta.env.VITE_MAKER_ID || 1
|
||||
export const CHECKER_ID = import.meta.env.VITE_CHECKER_ID || 2
|
||||
|
||||
export const isMaker = (role = decryptString(localStorage?.getItem("role"))) => role === import.meta.env.VITE_MAKER;
|
||||
export const isChecker = (role = decryptString(localStorage?.getItem("role"))) => role === import.meta.env.VITE_CHECKER;
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const TABLE_PAGINATION = { page: 1, size:20 }
|
||||
export const TABLE_PAGINATION = { page: 1, size: 20 }
|
||||
export const IMAGE_URI = import.meta.env.VITE_API_IMAGE_URL
|
||||
@@ -1,26 +1,48 @@
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import logo from "../assets/logo2.png";
|
||||
import logoDark from "../assets/logo.png";
|
||||
import logoMini from "../assets/logo-min.png";
|
||||
import logoMiniDark from "../assets/favicon.png";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { loginUser } from "../Redux/Slice/auth";
|
||||
import Button02 from "../Components/Buttons/Button02";
|
||||
import { CgProfile } from "react-icons/cg";
|
||||
import { useDispatch } from "react-redux";
|
||||
import logoMiniDark from "../assets/favicon.png";
|
||||
import logoMini from "../assets/logo-min.png";
|
||||
import logoDark from "../assets/logo.png";
|
||||
import logo from "../assets/logo2.png";
|
||||
|
||||
import {
|
||||
TbArrowBadgeLeftFilled,
|
||||
TbListDetails,
|
||||
TbReportMoney,
|
||||
TbTransactionDollar,
|
||||
} from "react-icons/tb";
|
||||
import { TbArrowBadgeRightFilled } from "react-icons/tb";
|
||||
import {
|
||||
ArrowBackIcon,
|
||||
ArrowLeftIcon,
|
||||
ArrowRightIcon,
|
||||
AtSignIcon,
|
||||
} from "@chakra-ui/icons";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionButton,
|
||||
AccordionIcon,
|
||||
AccordionItem,
|
||||
AccordionPanel,
|
||||
Alert,
|
||||
AlertIcon,
|
||||
Box,
|
||||
Button,
|
||||
Image,
|
||||
Text,
|
||||
Tooltip
|
||||
} from "@chakra-ui/react";
|
||||
import Cookies from "js-cookie"; // Import the Cookies library
|
||||
import { GrManual } from "react-icons/gr";
|
||||
import { HiOutlineChartSquareBar } from "react-icons/hi";
|
||||
import { LuContact } from "react-icons/lu";
|
||||
import { MdNotificationsNone, MdOutlineAddChart } from "react-icons/md";
|
||||
import {
|
||||
RiBankLine,
|
||||
RiExchangeBoxLine,
|
||||
RiFileUserLine,
|
||||
RiMoneyDollarBoxLine,
|
||||
} from "react-icons/ri";
|
||||
import {
|
||||
TbListDetails,
|
||||
TbReportMoney,
|
||||
TbTransactionDollar
|
||||
} from "react-icons/tb";
|
||||
import { VscSymbolClass } from "react-icons/vsc";
|
||||
import {
|
||||
Link,
|
||||
NavLink,
|
||||
@@ -29,71 +51,21 @@ import {
|
||||
useLocation,
|
||||
useNavigate,
|
||||
} from "react-router-dom";
|
||||
import { RouteLink } from "../Routes/Routes";
|
||||
import NotFound from "../Pages/NotFound";
|
||||
import { nav } from "../Routes/Nav";
|
||||
import {
|
||||
Avatar,
|
||||
Box,
|
||||
Button,
|
||||
PopoverArrow,
|
||||
PopoverBody,
|
||||
PopoverCloseButton,
|
||||
PopoverContent,
|
||||
PopoverFooter,
|
||||
PopoverHeader,
|
||||
PopoverTrigger,
|
||||
Portal,
|
||||
Text,
|
||||
WrapItem,
|
||||
Popover,
|
||||
Tag,
|
||||
Accordion,
|
||||
AccordionItem,
|
||||
AccordionButton,
|
||||
AccordionIcon,
|
||||
AccordionPanel,
|
||||
Image,
|
||||
Alert,
|
||||
AlertIcon,
|
||||
Breadcrumb,
|
||||
Divider,
|
||||
Tooltip,
|
||||
useRadio,
|
||||
} from "@chakra-ui/react";
|
||||
import GlobalStateContext from "../Contexts/GlobalStateContext";
|
||||
import Cookies from "js-cookie"; // Import the Cookies library
|
||||
import Header from "../Components/Header";
|
||||
import HeaderMain from "../Components/HeaderMain";
|
||||
import { IoMdSwap } from "react-icons/io";
|
||||
import {
|
||||
RiBankLine,
|
||||
RiExchangeBoxLine,
|
||||
RiFileUserLine,
|
||||
RiMoneyDollarBoxLine,
|
||||
} from "react-icons/ri";
|
||||
import { VscSymbolClass } from "react-icons/vsc";
|
||||
import { MdNotificationsNone, MdOutlineAddChart } from "react-icons/md";
|
||||
import { HiOutlineChartSquareBar } from "react-icons/hi";
|
||||
import { GrManual } from "react-icons/gr";
|
||||
import { LuContact } from "react-icons/lu";
|
||||
import shield from "../assets/shield.png";
|
||||
import SplashScreen from "../Pages/SplashScreen";
|
||||
import CutomBreadcrumb from "../Components/CutomBreadcrumb";
|
||||
import CustomBreadcrumb from "../Components/CutomBreadcrumb";
|
||||
import { getCountdownTimer } from "../Constants/Constants";
|
||||
import { useLogoutMutation } from "../Services/token.serivce";
|
||||
import GlobalStateContext from "../Contexts/GlobalStateContext";
|
||||
import CreateRequest from "../Pages/Fawateer/CreateRequest";
|
||||
import ApproveRequest from "../Pages/FawateerChecker/ApproveRequest/ApproveRequest";
|
||||
import ApproveHistoryMaker from "../Pages/FawateerChecker/ApproveHistory/ApproveHistoryMaker";
|
||||
import ApproveHistory from "../Pages/FawateerChecker/ApproveHistory/ApproveHistoryChecker";
|
||||
import ApproveHistoryMaker from "../Pages/FawateerChecker/ApproveHistory/ApproveHistoryMaker";
|
||||
import ApproveRequest from "../Pages/FawateerChecker/ApproveRequest/ApproveRequest";
|
||||
import NotFound from "../Pages/NotFound";
|
||||
import SplashScreen from "../Pages/SplashScreen";
|
||||
import { nav } from "../Routes/Nav";
|
||||
import { RouteLink } from "../Routes/Routes";
|
||||
import { useProfileQuery } from "../Services/io.service";
|
||||
import SubAdmin from "../Pages/SubAdmin/SubAdmin";
|
||||
import { useLogoutMutation } from "../Services/token.serivce";
|
||||
|
||||
const DashboardLayout = ({ isOnline }) => {
|
||||
const userRole = localStorage.getItem("role");
|
||||
const navigate = useNavigate();
|
||||
const dispach = useDispatch();
|
||||
const location = useLocation();
|
||||
const path = location.pathname;
|
||||
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
|
||||
@@ -110,15 +82,15 @@ const DashboardLayout = ({ isOnline }) => {
|
||||
|
||||
const { data, refetch } = useProfileQuery();
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!localStorage.getItem("accessToken") &&
|
||||
!localStorage.getItem("refreshToken")
|
||||
) {
|
||||
logOutHandler();
|
||||
return navigate("/login");
|
||||
}
|
||||
}, []);
|
||||
// useEffect(() => {
|
||||
// if (
|
||||
// !localStorage.getItem("accessToken") &&
|
||||
// !localStorage.getItem("refreshToken")
|
||||
// ) {
|
||||
// logOutHandler();
|
||||
// return navigate("/login");
|
||||
// }
|
||||
// }, []);
|
||||
|
||||
useEffect(() => {
|
||||
const savedIndex = localStorage.getItem("openAccordionIndex");
|
||||
@@ -157,7 +129,9 @@ const DashboardLayout = ({ isOnline }) => {
|
||||
await logout();
|
||||
localStorage.clear();
|
||||
navigate("/login");
|
||||
} catch (error) {}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
};
|
||||
|
||||
// // Function to get the title based on the route
|
||||
@@ -375,6 +349,13 @@ const DashboardLayout = ({ isOnline }) => {
|
||||
Deletion request
|
||||
</span>
|
||||
);
|
||||
case path.startsWith("/subadmin"):
|
||||
return (
|
||||
<span className="d-flex align-items-end gap-2">
|
||||
<RiMoneyDollarBoxLine className="h4 m-0 fw-normal" />
|
||||
Manage SubAdmin
|
||||
</span>
|
||||
);
|
||||
|
||||
default:
|
||||
if (path.startsWith("/community/view/")) {
|
||||
|
||||
@@ -1,27 +1,25 @@
|
||||
import {
|
||||
Avatar,
|
||||
Badge,
|
||||
Box,
|
||||
HStack,
|
||||
Input,
|
||||
Select,
|
||||
Switch,
|
||||
Text,
|
||||
useDisclosure,
|
||||
useToast,
|
||||
} from "@chakra-ui/react";
|
||||
import React, { useContext, useEffect, useState, useRef } from "react";
|
||||
import { Link, Link as RouterLink, useNavigate } from "react-router-dom";
|
||||
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
|
||||
import { debounce } from "../../../Master/Sponser/AddSponser";
|
||||
import { OPACITY_ON_LOAD } from "../../../../Layout/animations";
|
||||
import NormalTable from "../../../../Components/DataTable/NormalTable";
|
||||
import React, { useContext, useEffect, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import CustomAlertDialog from "../../../../Components/CustomAlertDialog";
|
||||
import Pagination from "../../../../Components/Pagination";
|
||||
import NormalTable from "../../../../Components/DataTable/NormalTable";
|
||||
import ToastBox from "../../../../Components/ToastBox";
|
||||
import ReasonBanModal from "./ReasonBanModal";
|
||||
import { useGetbanInvestorQuery } from "../../../../Services/ban.investor.service";
|
||||
import { TABLE_PAGINATION } from "../../../../Constants/Paginations";
|
||||
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
|
||||
import { OPACITY_ON_LOAD } from "../../../../Layout/animations";
|
||||
import { useGetbanInvestorQuery } from "../../../../Services/ban.investor.service";
|
||||
import { debounce } from "../../../Master/Sponser/AddSponser";
|
||||
import ReasonBanModal from "./ReasonBanModal";
|
||||
import Pagination from "../../../../Components/Pagination";
|
||||
|
||||
const formatDate = (date) => new Date(date).toLocaleDateString(); // Simple date formatter
|
||||
|
||||
@@ -233,8 +231,6 @@ const BankInvestor = () => {
|
||||
),
|
||||
}));
|
||||
|
||||
console.log(extractedArray);
|
||||
|
||||
const handleDelete = () => {
|
||||
const updatedInvestorDetails = InvestorDetails.filter(
|
||||
(sponsor) => sponsor.id !== actionId
|
||||
@@ -278,6 +274,14 @@ const BankInvestor = () => {
|
||||
/>
|
||||
|
||||
<HStack display={"flex"} alignItems={"center"}>
|
||||
<Pagination
|
||||
isLoading={unbanLoading}
|
||||
pageSize={pageSize}
|
||||
setPageSize={setPageSize}
|
||||
currentPage={currentPage}
|
||||
setCurrentPage={setCurrentPage}
|
||||
totalItems={data?.data?.totalItems}
|
||||
/>
|
||||
{/* <Select
|
||||
focusBorderColor="green.500"
|
||||
size={"sm"}
|
||||
|
||||
@@ -1,31 +1,26 @@
|
||||
import {
|
||||
Avatar,
|
||||
Badge,
|
||||
Box,
|
||||
HStack,
|
||||
Input,
|
||||
Select,
|
||||
Switch,
|
||||
Text,
|
||||
useDisclosure,
|
||||
useToast,
|
||||
} from "@chakra-ui/react";
|
||||
import React, { useContext, useEffect, useState, useRef } from "react";
|
||||
import { Link, Link as RouterLink, useNavigate } from "react-router-dom";
|
||||
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
|
||||
import { debounce } from "../../../Master/Sponser/AddSponser";
|
||||
import { OPACITY_ON_LOAD } from "../../../../Layout/animations";
|
||||
import DataTable from "../../../../Components/DataTable/NormalTable";
|
||||
import React, { useContext, useEffect, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import CustomAlertDialog from "../../../../Components/CustomAlertDialog";
|
||||
import Pagination from "../../../../Components/Pagination";
|
||||
import DataTable from "../../../../Components/DataTable/NormalTable";
|
||||
import ToastBox from "../../../../Components/ToastBox";
|
||||
import ReasonBanModal from "./ReasonBanModal";
|
||||
import {
|
||||
useGetInvestorQuery,
|
||||
useGetUnbanInvestorQuery,
|
||||
} from "../../../../Services/ban.investor.service";
|
||||
import { generateSerialNumber } from "../../../../Constants/Constants";
|
||||
import { TABLE_PAGINATION } from "../../../../Constants/Paginations";
|
||||
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
|
||||
import { OPACITY_ON_LOAD } from "../../../../Layout/animations";
|
||||
import { useGetUnbanInvestorQuery } from "../../../../Services/ban.investor.service";
|
||||
import { debounce } from "../../../Master/Sponser/AddSponser";
|
||||
import ReasonBanModal from "./ReasonBanModal";
|
||||
import Pagination from "../../../../Components/Pagination";
|
||||
|
||||
const formatDate = (date) => new Date(date).toLocaleDateString(); // Simple date formatter
|
||||
|
||||
@@ -270,6 +265,14 @@ const UnbanInvestor = () => {
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
<HStack display={"flex"} alignItems={"center"}>
|
||||
<Pagination
|
||||
isLoading={unbanLoading}
|
||||
pageSize={pageSize}
|
||||
setPageSize={setPageSize}
|
||||
currentPage={currentPage}
|
||||
setCurrentPage={setCurrentPage}
|
||||
totalItems={data?.data?.totalItems}
|
||||
/>
|
||||
{/* <Select
|
||||
focusBorderColor="green.500"
|
||||
size={"sm"}
|
||||
|
||||
@@ -16,14 +16,13 @@ import {
|
||||
Stack,
|
||||
useToast,
|
||||
} from "@chakra-ui/react";
|
||||
import * as yup from "yup";
|
||||
import React, { useState, useContext } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import React, { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import * as yup from "yup";
|
||||
import CustomAlertDialog from "../Components/CustomAlertDialog";
|
||||
import ToastBox from "../Components/ToastBox";
|
||||
import { useUpdatePasswordMutation } from "../Services/change.password.service";
|
||||
import { all } from "axios";
|
||||
|
||||
// Validation schema
|
||||
const passwordSchema = yup.object().shape({
|
||||
@@ -42,8 +41,8 @@ const passwordSchema = yup.object().shape({
|
||||
),
|
||||
confirmNewPassword: yup
|
||||
.string()
|
||||
.required("Confirm Password is required")
|
||||
.oneOf([yup.ref("newPassword")], "Passwords must match"),
|
||||
.required("Confirm New Password is required")
|
||||
.oneOf([yup.ref("newPassword")], "Password do not match"),
|
||||
});
|
||||
|
||||
const ChangePassword = ({
|
||||
@@ -53,12 +52,18 @@ const ChangePassword = ({
|
||||
actionId,
|
||||
setActionId,
|
||||
}) => {
|
||||
const initialValue = {
|
||||
oldPassword: "",
|
||||
newPassword: "",
|
||||
confirmNewPassword: "",
|
||||
};
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [alert, setAlert] = useState(false);
|
||||
const [showCurrentPassword, setShowCurrentPassword] = useState(false);
|
||||
const [showNewPassword, setShowNewPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const toast = useToast();
|
||||
const [input, setInput] = useState(initialValue);
|
||||
|
||||
const [updatePassword] = useUpdatePasswordMutation();
|
||||
|
||||
@@ -74,10 +79,10 @@ const ChangePassword = ({
|
||||
});
|
||||
|
||||
// Form submit handler
|
||||
const onSubmit = async (data) => {
|
||||
const onSubmit = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const res = await updatePassword(data); // Assuming API request works as expected
|
||||
const res = await updatePassword(input); // Assuming API request works as expected
|
||||
if (res?.data?.statusCode === 200) {
|
||||
toast({
|
||||
render: () => <ToastBox message={res?.data?.message} />,
|
||||
@@ -89,6 +94,7 @@ const ChangePassword = ({
|
||||
<ToastBox message={res?.error?.data?.message} status={"error"} />
|
||||
),
|
||||
});
|
||||
setAlert(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@@ -97,6 +103,11 @@ const ChangePassword = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmitFrom = (data) => {
|
||||
setAlert(true);
|
||||
setInput(data);
|
||||
};
|
||||
|
||||
// Handle modal close
|
||||
const handleClose = () => {
|
||||
setAlert(false);
|
||||
@@ -106,7 +117,7 @@ const ChangePassword = ({
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal isOpen={isOpen} onClose={onClose} initialFocusRef={firstField}>
|
||||
<Modal isOpen={isOpen} onClose={handleClose} initialFocusRef={firstField}>
|
||||
<ModalOverlay />
|
||||
<ModalContent>
|
||||
<ModalHeader fontSize="md">Change Password</ModalHeader>
|
||||
@@ -114,7 +125,7 @@ const ChangePassword = ({
|
||||
<ModalBody pb={6}>
|
||||
<Stack spacing={4}>
|
||||
{/* Current Password */}
|
||||
<FormControl isInvalid={errors.oldPassword}>
|
||||
<FormControl isInvalid={errors.oldPassword} isRequired>
|
||||
<FormLabel fontSize="sm" mb={1} fontWeight={500}>
|
||||
Current Password
|
||||
</FormLabel>
|
||||
@@ -141,7 +152,7 @@ const ChangePassword = ({
|
||||
</FormControl>
|
||||
|
||||
{/* New Password */}
|
||||
<FormControl isInvalid={errors.newPassword}>
|
||||
<FormControl isInvalid={errors.newPassword} isRequired>
|
||||
<FormLabel fontSize="sm" mb={1}>
|
||||
New Password
|
||||
</FormLabel>
|
||||
@@ -168,7 +179,7 @@ const ChangePassword = ({
|
||||
</FormControl>
|
||||
|
||||
{/* Confirm Password */}
|
||||
<FormControl isInvalid={errors.confirmNewPassword}>
|
||||
<FormControl isInvalid={errors.confirmNewPassword} isRequired>
|
||||
<FormLabel fontSize="sm" mb={1}>
|
||||
Confirm New Password
|
||||
</FormLabel>
|
||||
@@ -210,7 +221,8 @@ const ChangePassword = ({
|
||||
rounded={"sm"}
|
||||
colorScheme="forestGreen"
|
||||
size="sm"
|
||||
onClick={() => setAlert(true)}
|
||||
// onClick={() => setAlert(true)}
|
||||
onClick={handleSubmit(handleSubmitFrom)}
|
||||
isLoading={isLoading}
|
||||
>
|
||||
Save
|
||||
@@ -222,7 +234,7 @@ const ChangePassword = ({
|
||||
<CustomAlertDialog
|
||||
isOpen={alert}
|
||||
onClose={() => setAlert(false)}
|
||||
alertHandler={handleSubmit(onSubmit)}
|
||||
alertHandler={onSubmit}
|
||||
message={"Are you sure you want to change the password?"}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
useToast,
|
||||
} from "@chakra-ui/react";
|
||||
import * as yup from "yup";
|
||||
import React, { useState} from "react";
|
||||
import React, { useState } from "react";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import { useForgetPasswordMutation } from "../Services/forget.password.service";
|
||||
@@ -25,7 +25,9 @@ const validationSchema = yup.object().shape({
|
||||
emailAddress: yup
|
||||
.string()
|
||||
.email("Invalid email format")
|
||||
.required("Email, Phone, or Username is required"),
|
||||
.required("Email address is required")
|
||||
.min(6, "Email address must be at least 6 characters long")
|
||||
.max(255, "Email address can be at most 255 characters long"),
|
||||
});
|
||||
|
||||
const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
@@ -38,12 +40,12 @@ const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
reset, // Add reset from useForm
|
||||
} = useForm({
|
||||
resolver: yupResolver(validationSchema),
|
||||
});
|
||||
|
||||
const onSubmit = async (formData) => {
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const res = await forgetPassword(formData);
|
||||
@@ -52,13 +54,14 @@ const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
render: () => <ToastBox message={res?.data?.message} />,
|
||||
});
|
||||
handleClose();
|
||||
} else if (res?.error?.status === 401) {
|
||||
} else if (res?.error?.status === 400) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox message={res?.error?.data?.message} status="error" />
|
||||
),
|
||||
});
|
||||
handleClose();
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@@ -70,6 +73,7 @@ const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
const handleClose = () => {
|
||||
setIsLoading(false);
|
||||
onClose();
|
||||
reset(); // Reset form state when modal closes
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -82,13 +86,13 @@ const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
<ModalOverlay />
|
||||
<ModalContent>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<ModalHeader fontSize="md">Forget Password</ModalHeader>
|
||||
<ModalHeader fontSize="md">Forgot Password</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody pb={4}>
|
||||
<Stack spacing={4}>
|
||||
<FormControl isInvalid={errors.emailAddress}>
|
||||
<FormControl isInvalid={errors.emailAddress} isRequired>
|
||||
<FormLabel fontSize="sm" mb={3} fontWeight={500}>
|
||||
Email, Phone, or Username
|
||||
Please Enter Email Address
|
||||
</FormLabel>
|
||||
<Controller
|
||||
name="emailAddress"
|
||||
@@ -98,7 +102,7 @@ const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
{...field}
|
||||
size="md"
|
||||
fontSize="sm"
|
||||
focusBorderColor="forestGreen.300"
|
||||
focusBorderColor="forestGreen.300"
|
||||
rounded={4}
|
||||
type="text"
|
||||
/>
|
||||
@@ -114,7 +118,7 @@ const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
<DrawerFooter mb={5}>
|
||||
<Button
|
||||
w="100%"
|
||||
colorScheme="forestGreen"
|
||||
colorScheme="forestGreen"
|
||||
rounded="md"
|
||||
size="md"
|
||||
type="submit"
|
||||
@@ -122,7 +126,7 @@ const ForgetPassword = ({ isOpen, onClose, firstField }) => {
|
||||
fontWeight={400}
|
||||
fontSize="sm"
|
||||
>
|
||||
Send Login Link
|
||||
Reset Password
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
</form>
|
||||
|
||||
@@ -20,7 +20,7 @@ import AddCaseDetails from "./AddCaseDetails";
|
||||
import { useUpdateIOCaseMutation } from "../../../../Services/io.service";
|
||||
import ToastBox from "../../../../Components/ToastBox";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { encryptString } from "../../../../Constants/Constants";
|
||||
import { encryptString, isMaker } from "../../../../Constants/Constants";
|
||||
|
||||
const IOCashDetails = () => {
|
||||
const params = useParams();
|
||||
@@ -88,7 +88,8 @@ const IOCashDetails = () => {
|
||||
Pending
|
||||
{IODetails?.ioCashStatusHistory?.Pending.length > 0 && (
|
||||
<Badge rounded={"sm"} colorScheme="forestGreen" ms={2}>
|
||||
{IODetails?.ioCashStatusHistory?.Pending.length !== 0 && IODetails?.ioCashStatusHistory?.Pending.length}
|
||||
{IODetails?.ioCashStatusHistory?.Pending.length !== 0 &&
|
||||
IODetails?.ioCashStatusHistory?.Pending.length}
|
||||
</Badge>
|
||||
)}
|
||||
{/* <Badge rounded={"sm"} colorScheme="forestGreen" ms={2}>
|
||||
@@ -106,7 +107,7 @@ const IOCashDetails = () => {
|
||||
</Tab>
|
||||
</TabList>
|
||||
{IODetails?.isInvestedAmount
|
||||
? localStorage?.getItem("role") === encryptString(import.meta.env.VITE_VITE_MAKER) && (
|
||||
? isMaker() && (
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
leftIcon={<AddIcon />}
|
||||
|
||||
@@ -235,7 +235,6 @@ const IODetails = ({ enableNextTab, index, data }) => {
|
||||
|
||||
const [values, setValues] = useState(id?minInvestmentById:miniValue);
|
||||
|
||||
console.log(values);
|
||||
|
||||
const formatNumber = (num) => {
|
||||
// Remove non-numeric characters and format with commas
|
||||
|
||||
@@ -75,7 +75,7 @@ import ToastBox from "../../../../Components/ToastBox";
|
||||
import { useParams } from "react-router-dom";
|
||||
import AddNavDetails from "./AddNavDetails";
|
||||
import { useUpdateIOCaseMutation } from "../../../../Services/io.service";
|
||||
import { encryptString } from "../../../../Constants/Constants";
|
||||
import { encryptString, isMaker } from "../../../../Constants/Constants";
|
||||
|
||||
const IONAVDetails = () => {
|
||||
const params = useParams();
|
||||
@@ -153,7 +153,7 @@ const IONAVDetails = () => {
|
||||
</Tab>
|
||||
</TabList>
|
||||
{IODetails?.isInvestedAmount
|
||||
? localStorage?.getItem("role") === encryptString(import.meta.env.VITE_VITE_MAKER) && (
|
||||
? isMaker() && (
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
leftIcon={<AddIcon />}
|
||||
|
||||
@@ -27,7 +27,7 @@ import ViewAmountInvested from "./ViewAmountInvested";
|
||||
import ViewDistributionInvestor from "./ViewDistributionInvestor";
|
||||
import ViewExit from "./ViewExit";
|
||||
import ViewCancel from "./ViewCancel";
|
||||
import { encryptString } from "../../../../Constants/Constants";
|
||||
import { encryptString, isMaker } from "../../../../Constants/Constants";
|
||||
|
||||
const formatDate = (date) => new Date(date).toLocaleDateString();
|
||||
|
||||
@@ -128,11 +128,7 @@ const Pending = () => {
|
||||
</Text>
|
||||
),
|
||||
"Transaction Date": (
|
||||
<Text
|
||||
as={"span"}
|
||||
color={"gray.600"}
|
||||
fontWeight={"500"}
|
||||
>
|
||||
<Text as={"span"} color={"gray.600"} fontWeight={"500"}>
|
||||
{formatDate(item?.transactionDate)}
|
||||
</Text>
|
||||
),
|
||||
@@ -153,8 +149,13 @@ const Pending = () => {
|
||||
</Text>
|
||||
),
|
||||
"Created By": (
|
||||
<Text
|
||||
textTransform={'capitalize'} w={"100px"} as={"span"} color={"gray.800"} fontWeight={"500"}>
|
||||
<Text
|
||||
textTransform={"capitalize"}
|
||||
w={"100px"}
|
||||
as={"span"}
|
||||
color={"gray.800"}
|
||||
fontWeight={"500"}
|
||||
>
|
||||
{item?.creator?.firstName}
|
||||
</Text>
|
||||
),
|
||||
@@ -164,8 +165,13 @@ const Pending = () => {
|
||||
</Text>
|
||||
),
|
||||
"Approved By": (
|
||||
<Text
|
||||
textTransform={'capitalize'} w={"100px"} as={"span"} color={"gray.800"} fontWeight={"500"}>
|
||||
<Text
|
||||
textTransform={"capitalize"}
|
||||
w={"100px"}
|
||||
as={"span"}
|
||||
color={"gray.800"}
|
||||
fontWeight={"500"}
|
||||
>
|
||||
{item?.modifier?.firstName}
|
||||
</Text>
|
||||
),
|
||||
@@ -196,7 +202,11 @@ const Pending = () => {
|
||||
}
|
||||
}}
|
||||
>
|
||||
{localStorage?.getItem("role") === encryptString(import.meta.env.VITE_VITE_MAKER) ? <ViewIcon me={"4px"} /> : null} {localStorage?.getItem("role") === encryptString(import.meta.env.VITE_VITE_MAKER) ? "View" : "Approve / Reject"}
|
||||
{isMaker() ? <ViewIcon me={"4px"} /> : null}{" "}
|
||||
{localStorage?.getItem("role") ===
|
||||
encryptString(import.meta.env.VITE_VITE_MAKER)
|
||||
? "View"
|
||||
: "Approve / Reject"}
|
||||
</Button>
|
||||
</Box>
|
||||
),
|
||||
@@ -263,20 +273,12 @@ const Pending = () => {
|
||||
id={actionId}
|
||||
/>
|
||||
<ViewDistributionInvestor
|
||||
isOpen={isDistInvestorOpen}
|
||||
onClose={onDistInvestorClose}
|
||||
id={actionId}
|
||||
/>
|
||||
<ViewExit
|
||||
isOpen={isExitOpen}
|
||||
onClose={onExitClose}
|
||||
isOpen={isDistInvestorOpen}
|
||||
onClose={onDistInvestorClose}
|
||||
id={actionId}
|
||||
/>
|
||||
<ViewCancel
|
||||
isOpen={isCancelOpen}
|
||||
onClose={onCancelClose}
|
||||
id={actionId}
|
||||
/>
|
||||
<ViewExit isOpen={isExitOpen} onClose={onExitClose} id={actionId} />
|
||||
<ViewCancel isOpen={isCancelOpen} onClose={onCancelClose} id={actionId} />
|
||||
<RequestApproveModal
|
||||
// data={data?.data?.rows}
|
||||
isOpen={isConfirmOpen}
|
||||
|
||||
@@ -1,57 +1,29 @@
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
|
||||
import {
|
||||
Box,
|
||||
Divider,
|
||||
FormControl,
|
||||
FormLabel,
|
||||
Heading,
|
||||
Input,
|
||||
Select,
|
||||
Textarea,
|
||||
Button,
|
||||
Text,
|
||||
Image,
|
||||
Tabs,
|
||||
TabList,
|
||||
Tab,
|
||||
TabList,
|
||||
TabPanel,
|
||||
TabPanels,
|
||||
Tooltip,
|
||||
Switch,
|
||||
Tabs,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import * as yup from "yup";
|
||||
import {
|
||||
AddIcon,
|
||||
CloseIcon,
|
||||
DeleteIcon,
|
||||
EditIcon,
|
||||
ViewIcon,
|
||||
WarningTwoIcon,
|
||||
} from "@chakra-ui/icons";
|
||||
import { TiWarning } from "react-icons/ti";
|
||||
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import FormField from "../../../Components/FormField";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import AddIOCharges from "../AddIOCharges";
|
||||
import FormInputMain from "../../../Components/FormInputMain";
|
||||
import DataTable from "../../../Components/DataTable/DataTable";
|
||||
import { debounce } from "../../Master/Sponser/AddSponser";
|
||||
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
|
||||
import { formatDate } from "../../../Components/Functions/UTCConvertor";
|
||||
import IODetails from "./IODetails";
|
||||
import KeyMerits from "./KeyMerits";
|
||||
import IOArtifacts from "./IOArtifacts";
|
||||
import Investors from "./Investors";
|
||||
import IOCashDetails from "./IOCashDetails";
|
||||
import IONAVDetails from "./IONAVDetails";
|
||||
import * as yup from "yup";
|
||||
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
|
||||
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
|
||||
import Distribution from "./Destribution";
|
||||
import InvestmentDocuments from "../InvestmentDocuments";
|
||||
import InvestmentDocument from "./InvestmentDocument";
|
||||
import Investors from "./Investors";
|
||||
import IOArtifacts from "./IOArtifacts";
|
||||
import IOCashDetails from "./IOCashDetails";
|
||||
import IODetails from "./IODetails";
|
||||
import IONAVDetails from "./IONAVDetails";
|
||||
import KeyMerits from "./KeyMerits";
|
||||
import { useAuthProfileQuery } from "../../Services/token.serivce";
|
||||
import { encryptString } from "../../Constants/Constants";
|
||||
|
||||
const schema = yup.object().shape({
|
||||
ioName: yup.string().required("Arabic name is required"),
|
||||
@@ -59,7 +31,9 @@ const schema = yup.object().shape({
|
||||
discription: yup.string().required("Description is required"),
|
||||
discriptionArabic: yup.string().required("Arabic Description is required"),
|
||||
typeName: yup.string().required("Investment type is required"),
|
||||
typeNameArabic: yup.string().required("Investment type arabic name is required"),
|
||||
typeNameArabic: yup
|
||||
.string()
|
||||
.required("Investment type arabic name is required"),
|
||||
sponserName: yup.string().required("Sponsorer name is required"),
|
||||
sponserNameArabic: yup
|
||||
.string()
|
||||
@@ -293,7 +267,7 @@ const EditViewIO = () => {
|
||||
isRequired: true,
|
||||
section: " ",
|
||||
width: "32.3%",
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Name (Arabic)",
|
||||
placeHolder: " ",
|
||||
|
||||
@@ -58,7 +58,7 @@ const UpdateIOStatus = ({ isOpen, onClose, status }) => {
|
||||
let res;
|
||||
|
||||
// If selectedItem is 'Cancelled', make the updateCancelStatus API call
|
||||
if (selectedItem === "Cancelled") {
|
||||
if (selectedItem === import.meta.env.VITE_STATUS_CANCELLED) {
|
||||
res = await updateCancleStatus({
|
||||
id
|
||||
});
|
||||
@@ -119,17 +119,17 @@ const UpdateIOStatus = ({ isOpen, onClose, status }) => {
|
||||
mb={1.5}
|
||||
textTransform={"none"}
|
||||
colorScheme={
|
||||
selectedItem === "Draft"
|
||||
selectedItem === import.meta.env.VITE_STATUS_DRAFT
|
||||
? "gray"
|
||||
: selectedItem === "Processing"
|
||||
: selectedItem === import.meta.env.VITE_STATUS_PROCESSING
|
||||
? "yellow"
|
||||
: selectedItem === "Open"
|
||||
: selectedItem === import.meta.env.VITE_STATUS_OPEN
|
||||
? "blue"
|
||||
: selectedItem === "Closed"
|
||||
: selectedItem === import.meta.env.VITE_STATUS_CLOSED
|
||||
? "green"
|
||||
: selectedItem === "Exited"
|
||||
: selectedItem === import.meta.env.VITE_STATUS_EXITED
|
||||
? "red"
|
||||
: selectedItem === "Cancelled"
|
||||
: selectedItem === import.meta.env.VITE_STATUS_CANCELLED
|
||||
? "orange"
|
||||
: "purple"
|
||||
}
|
||||
@@ -154,24 +154,24 @@ const UpdateIOStatus = ({ isOpen, onClose, status }) => {
|
||||
<Badge
|
||||
rounded={"full"}
|
||||
pt={1.5}
|
||||
pb={1.5}
|
||||
pb={1.5}
|
||||
ps={4}
|
||||
pe={4}
|
||||
mt={1.5}
|
||||
mb={1.5}
|
||||
textTransform={"none"}
|
||||
colorScheme={
|
||||
statusAdmin === "Draft"
|
||||
statusAdmin === import.meta.env.VITE_STATUS_DRAFT
|
||||
? "gray"
|
||||
: statusAdmin === "Processing"
|
||||
: statusAdmin === import.meta.env.VITE_STATUS_PROCESSING
|
||||
? "yellow"
|
||||
: statusAdmin === "Open"
|
||||
: statusAdmin === import.meta.env.VITE_STATUS_OPEN
|
||||
? "blue"
|
||||
: statusAdmin === "Closed"
|
||||
: statusAdmin === import.meta.env.VITE_STATUS_CLOSED
|
||||
? "green"
|
||||
: statusAdmin === "Exited"
|
||||
: statusAdmin === import.meta.env.VITE_STATUS_EXITED
|
||||
? "red"
|
||||
: statusAdmin === "Cancelled"
|
||||
: statusAdmin === import.meta.env.VITE_STATUS_CANCELLED
|
||||
? "orange"
|
||||
: "purple"
|
||||
}
|
||||
|
||||
@@ -97,7 +97,6 @@ const ViewIOTable = () => {
|
||||
skip: debouncedSearchTerm === "" && searchTerm !== "", // Skip if search is empty and it's not the initial request
|
||||
});
|
||||
|
||||
console.log(data);
|
||||
|
||||
// ===============================[ Table Header ]
|
||||
const tableHeadRow = [
|
||||
@@ -242,17 +241,17 @@ const ViewIOTable = () => {
|
||||
textTransform={"none"}
|
||||
// variant={"solid"}
|
||||
colorScheme={
|
||||
item?.ioStatus?.statusAdmin === "Draft"
|
||||
item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_DRAFT
|
||||
? "gray"
|
||||
: item?.ioStatus?.statusAdmin === "Processing"
|
||||
: item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_PROCESSING
|
||||
? "yellow"
|
||||
: item?.ioStatus?.statusAdmin === "Open"
|
||||
: item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_OPEN
|
||||
? "blue"
|
||||
: item?.ioStatus?.statusAdmin === "Closed"
|
||||
: item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CLOSED
|
||||
? "green"
|
||||
: item?.ioStatus?.statusAdmin === "Exited"
|
||||
: item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_EXITED
|
||||
? "red"
|
||||
: item?.ioStatus?.statusAdmin === "Canclled"
|
||||
: item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CANCELLED
|
||||
? "orange"
|
||||
: "purple"
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Icon,
|
||||
Input,
|
||||
keyframes,
|
||||
Stack,
|
||||
Tab,
|
||||
@@ -10,40 +8,29 @@ import {
|
||||
TabPanel,
|
||||
TabPanels,
|
||||
Tabs,
|
||||
Text,
|
||||
useDisclosure,
|
||||
useDisclosure
|
||||
} from "@chakra-ui/react";
|
||||
import { useContext, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import FormInputView from "../../../Components/FormInputView";
|
||||
import { useForm } from "react-hook-form"; // assuming react-hook-form is used
|
||||
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
|
||||
import { ArrowBackIcon, RepeatIcon } from "@chakra-ui/icons";
|
||||
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
|
||||
import InvestmentDocument from "../CreateIO/InvestmentDocument";
|
||||
import Investors from "../CreateIO/Investors";
|
||||
import IOArtifacts from "../CreateIO/IOArtifacts";
|
||||
import KeyMerits from "../CreateIO/KeyMerits";
|
||||
import ViewIOdataHeader from "./ViewIOdataHeader";
|
||||
import ViewIOdetails from "./ViewIOdetails";
|
||||
import ViewIOdocs from "./ViewIOdocs";
|
||||
import ViewKeyMerits from "./ViewKeyMerits";
|
||||
import ViewIOartifacts from "./ViewIOartifacts";
|
||||
import ViewInvestors from "./ViewInvestors";
|
||||
import ViewIOcash from "./ViewIOcash";
|
||||
import ViewIOnav from "./ViewIOnav";
|
||||
import ViewDistribution from "./ViewDistribution";
|
||||
import InvestmentDocument from "../CreateIO/InvestmentDocument";
|
||||
import KeyMerits from "../CreateIO/KeyMerits";
|
||||
import Investors from "../CreateIO/Investors";
|
||||
import EditIO from "../EditIO/EditIO";
|
||||
import IOArtifacts from "../CreateIO/IOArtifacts";
|
||||
// import IOCashDetails from "../CreateIO/IOCashDetailsold";
|
||||
// import IONAVDetails from "../CreateIO/IONAVDetailsOld";
|
||||
import { useGetIOByIdQuery, useGetIOprepopulateDataQuery } from "../../../Services/io.service";
|
||||
import UnderConstruction from "../../UnderConstruction";
|
||||
import { GoDotFill } from "react-icons/go";
|
||||
import {
|
||||
useGetIOByIdQuery,
|
||||
useGetIOprepopulateDataQuery,
|
||||
} from "../../../Services/io.service";
|
||||
import Destribution from "../CreateIO/Destribution";
|
||||
import IOCashDetails from "../CreateIO/IOCashDetails/IOCashDetails";
|
||||
import IONAVDetails from "../CreateIO/IONAVDetails/IONAVDetails";
|
||||
import IOTransaction from "../CreateIO/IOTransaction/IOTransaction";
|
||||
import { GoDotFill } from "react-icons/go";
|
||||
|
||||
const rotate = keyframes`
|
||||
from {
|
||||
@@ -69,7 +56,6 @@ const ViewIOdata = () => {
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isRefetchLoading, setIsRefetchLoading] = useState(false);
|
||||
const { IODetails, setIODetails } = useContext(GlobalStateContext);
|
||||
console.log(IODetails?.isInvestedAmount);
|
||||
|
||||
const tabs = [
|
||||
{ label: "IO Details", content: <ViewIOdetails data={data?.data} /> },
|
||||
@@ -193,13 +179,19 @@ const ViewIOdata = () => {
|
||||
cursor={"pointer"}
|
||||
/>
|
||||
</Box> */}
|
||||
<Stack position={"absolute"} right={1} bottom={1} direction="row" spacing={4}>
|
||||
<Stack
|
||||
position={"absolute"}
|
||||
right={1}
|
||||
bottom={1}
|
||||
direction="row"
|
||||
spacing={4}
|
||||
>
|
||||
<Button
|
||||
isLoading={isRefetchLoading}
|
||||
loadingText="Refresh"
|
||||
colorScheme="forestGreen"
|
||||
variant="solid"
|
||||
size={'xs'}
|
||||
size={"xs"}
|
||||
onClick={handleRefresh}
|
||||
fontWeight={400}
|
||||
>
|
||||
|
||||
@@ -1,61 +1,59 @@
|
||||
import {
|
||||
Button,
|
||||
Divider,
|
||||
Badge,
|
||||
Box,
|
||||
HStack,
|
||||
Icon,
|
||||
Image,
|
||||
Menu,
|
||||
MenuButton,
|
||||
MenuItem,
|
||||
MenuList,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalCloseButton,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
Portal,
|
||||
Text,
|
||||
useDisclosure,
|
||||
MenuItemOption,
|
||||
MenuGroup,
|
||||
MenuOptionGroup,
|
||||
MenuDivider,
|
||||
Badge,
|
||||
Box,
|
||||
Icon,
|
||||
HStack,
|
||||
useToast,
|
||||
} from "@chakra-ui/react";
|
||||
import header from "../../../assets/IOheader.png";
|
||||
import { useContext, useRef } from "react";
|
||||
import { GrGallery } from "react-icons/gr";
|
||||
import { HiDotsVertical } from "react-icons/hi";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { useParams } from "react-router-dom";
|
||||
import Loader01 from "../../../Components/Loaders/Loader01";
|
||||
import ToastBox from "../../../Components/ToastBox";
|
||||
import {
|
||||
decryptString,
|
||||
encryptString,
|
||||
isMaker,
|
||||
} from "../../../Constants/Constants";
|
||||
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
|
||||
import { useUpdateTransactionMutation } from "../../../Services/io.service";
|
||||
import AmountInvested from "./HeaderModal/AmountInvested";
|
||||
import FeesExpenses from "./HeaderModal/FeesExpenses";
|
||||
import DistributionSponsor from "./HeaderModal/DistributionSponsor";
|
||||
import Cancle from "./HeaderModal/Cancle";
|
||||
import DistributionInvestor from "./HeaderModal/DistributionInvestor";
|
||||
import DistributionSponsor from "./HeaderModal/DistributionSponsor";
|
||||
import Exit from "./HeaderModal/Exit";
|
||||
import FeesExpenses from "./HeaderModal/FeesExpenses";
|
||||
import UpdateIONav from "./HeaderModal/UpdateIONav";
|
||||
import UpdateIOStatus from "./HeaderModal/UpdateIOStatus";
|
||||
import { useContext, useRef } from "react";
|
||||
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
|
||||
import Exit from "./HeaderModal/Exit";
|
||||
import Cancle from "./HeaderModal/Cancle";
|
||||
import { AddIcon } from "@chakra-ui/icons";
|
||||
import { GrGallery } from "react-icons/gr";
|
||||
import Loader01 from "../../../Components/Loaders/Loader01";
|
||||
import { useUpdateTransactionMutation } from "../../../Services/io.service";
|
||||
import ToastBox from "../../../Components/ToastBox";
|
||||
import { encryptString } from "../../../Constants/Constants";
|
||||
import { useAuthProfileQuery } from "../../../Services/token.serivce";
|
||||
// import { formatCurrency } from "../../../Components/CurrencyInput";
|
||||
// import { removeTrailingZeros } from "../../../Constants/Constants";
|
||||
|
||||
const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
const params = useParams()
|
||||
const toast = useToast();
|
||||
const id = params?.id
|
||||
const params = useParams();
|
||||
const toast = useToast();
|
||||
const id = params?.id;
|
||||
const { isOpen, onOpen, onClose } = useDisclosure();
|
||||
const btnRef = useRef();
|
||||
const { IODetails, isIOloading } = useContext(GlobalStateContext);
|
||||
|
||||
const { data: authProfile } = useAuthProfileQuery();
|
||||
if (authProfile?.data?.role) {
|
||||
localStorage.setItem("role", encryptString(authProfile.data.role));
|
||||
} else {
|
||||
console.warn("Role is undefined or null. Skipping localStorage update.");
|
||||
}
|
||||
|
||||
|
||||
|
||||
const {
|
||||
isOpen: isInvestmentOpen,
|
||||
onOpen: onInvestmentOpen,
|
||||
@@ -107,95 +105,83 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
fontSize: "0.875rem",
|
||||
fontWeight: "400",
|
||||
};
|
||||
|
||||
const [updateTransaction] = useUpdateTransactionMutation();
|
||||
|
||||
console.log(
|
||||
import.meta.env.VITE_IMAGE_URL +
|
||||
IODetails?.artifactsImage?.[0]?.artifactPathName
|
||||
);
|
||||
|
||||
const [updateTransaction] = useUpdateTransactionMutation()
|
||||
|
||||
const handleDistributionInvestors = async () =>{
|
||||
|
||||
const handleDistributionInvestors = async () => {
|
||||
try {
|
||||
const res = await updateTransaction(id)
|
||||
|
||||
if (res?.data) {
|
||||
const res = await updateTransaction(id);
|
||||
|
||||
if (res?.data) {
|
||||
// toast({
|
||||
// render: () => (
|
||||
// <ToastBox status={"success"} message={res?.data?.message} />
|
||||
// ),
|
||||
// });
|
||||
// setIsLoading(false);
|
||||
onDistInvestorOpen()
|
||||
|
||||
} else if (res?.error) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox status={"error"} message={res?.error?.data?.message} />
|
||||
),
|
||||
});
|
||||
onDistInvestorOpen();
|
||||
} else if (res?.error) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox status={"error"} message={res?.error?.data?.message} />
|
||||
),
|
||||
});
|
||||
// setIsLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleExit = async () =>{
|
||||
|
||||
const handleExit = async () => {
|
||||
try {
|
||||
const res = await updateTransaction(id)
|
||||
|
||||
if (res?.data) {
|
||||
const res = await updateTransaction(id);
|
||||
|
||||
if (res?.data) {
|
||||
// toast({
|
||||
// render: () => (
|
||||
// <ToastBox status={"success"} message={res?.data?.message} />
|
||||
// ),
|
||||
// });
|
||||
// setIsLoading(false);
|
||||
onExitOpen()
|
||||
|
||||
} else if (res?.error) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox status={"error"} message={res?.error?.data?.message} />
|
||||
),
|
||||
});
|
||||
onExitOpen();
|
||||
} else if (res?.error) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox status={"error"} message={res?.error?.data?.message} />
|
||||
),
|
||||
});
|
||||
// setIsLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleInvestment = async () =>{
|
||||
|
||||
const handleInvestment = async () => {
|
||||
try {
|
||||
const res = await updateTransaction(id)
|
||||
|
||||
if (res?.data) {
|
||||
const res = await updateTransaction(id);
|
||||
|
||||
if (res?.data) {
|
||||
// toast({
|
||||
// render: () => (
|
||||
// <ToastBox status={"success"} message={res?.data?.message} />
|
||||
// ),
|
||||
// });
|
||||
// setIsLoading(false);
|
||||
onInvestmentOpen()
|
||||
|
||||
} else if (res?.error) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox status={"error"} message={res?.error?.data?.message} />
|
||||
),
|
||||
});
|
||||
onInvestmentOpen();
|
||||
} else if (res?.error) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox status={"error"} message={res?.error?.data?.message} />
|
||||
),
|
||||
});
|
||||
// setIsLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
const menu = [
|
||||
{
|
||||
@@ -217,7 +203,7 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
id: 6,
|
||||
title: "Distribution To Investors",
|
||||
onClickFunction: handleDistributionInvestors,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: "Update IO NAV",
|
||||
@@ -251,8 +237,8 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
apiTransactionTitles?.includes(item.id)
|
||||
);
|
||||
|
||||
|
||||
const balanceAmount = IODetails?.goalAmount - IODetails?.totalAmtInvestmentInUSD
|
||||
const balanceAmount =
|
||||
IODetails?.goalAmount - IODetails?.totalAmtInvestmentInUSD;
|
||||
|
||||
return IODetails?.investmentNameEnglish ? (
|
||||
<Box
|
||||
@@ -261,19 +247,19 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
justifyContent={"space-between"}
|
||||
gap={8}
|
||||
bg={
|
||||
IODetails?.ioStatus?.statusAdmin === "Draft"
|
||||
IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_DRAFT
|
||||
? "#EDF2F7"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Processing"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_PROCESSING
|
||||
? "#FEFBBF"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Open"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_OPEN
|
||||
? "#BEE2F8"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Closed"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CLOSED
|
||||
? "#C6F6D5"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Exited"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_EXITED
|
||||
? "#FED7D7"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Cancelled"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CANCELLED
|
||||
? "#E9D8FD"
|
||||
: IODetails?.ioStatus?.statusAdmin === "DeActivate"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_DEACTIVATE
|
||||
? "#E9D8FD"
|
||||
: null
|
||||
}
|
||||
@@ -318,7 +304,6 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
|
||||
<Box display={"flex"} gap={2} pb={1}>
|
||||
<Text
|
||||
as={"span"}
|
||||
@@ -336,7 +321,7 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
<Box display={"flex"} gap={2} pb={1}>
|
||||
<Box display={"flex"} gap={2} pb={1}>
|
||||
<Text
|
||||
as={"span"}
|
||||
fontSize={"xs"}
|
||||
@@ -353,7 +338,7 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
<Box display={"flex"} gap={2} pb={1}>
|
||||
<Box display={"flex"} gap={2} pb={1}>
|
||||
<Text
|
||||
as={"span"}
|
||||
fontSize={"xs"}
|
||||
@@ -364,18 +349,13 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
IO ID :-
|
||||
</Text>
|
||||
<Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
|
||||
{IODetails?.io_id
|
||||
? IODetails?.io_id
|
||||
: "---"}
|
||||
{IODetails?.io_id ? IODetails?.io_id : "---"}
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
</Box>
|
||||
|
||||
</HStack>
|
||||
|
||||
<Box gap={8} me={12} w={"220px"}>
|
||||
|
||||
<Box gap={8} me={12} w={"220px"}>
|
||||
<Box display={"flex"} justifyContent={"space-between"} gap={2} pb={1}>
|
||||
<Text
|
||||
as={"span"}
|
||||
@@ -405,10 +385,13 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
</Text>
|
||||
<Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
|
||||
{/* {IODetails?.ioCash ? formatCurrency(removeTrailingZeros(IODetails?.ioCash)) : "00.00"} */}
|
||||
{parseFloat(IODetails?.totalAmtInvestmentInUSD || 0).toLocaleString(undefined, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}
|
||||
{parseFloat(IODetails?.totalAmtInvestmentInUSD || 0).toLocaleString(
|
||||
undefined,
|
||||
{
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}
|
||||
)}
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
@@ -449,17 +432,17 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
textTransform={"none"}
|
||||
// variant={"solid"}
|
||||
colorScheme={
|
||||
IODetails?.ioStatus?.statusAdmin === "Draft"
|
||||
IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_DRAFT
|
||||
? "gray"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Processing"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_PROCESSING
|
||||
? "yellow"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Open"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_OPEN
|
||||
? "blue"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Closed"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CLOSED
|
||||
? "green"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Exited"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_EXITED
|
||||
? "red"
|
||||
: IODetails?.ioStatus?.statusAdmin === "Cancelled"
|
||||
: IODetails?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CANCELLED
|
||||
? "purple"
|
||||
: "purple"
|
||||
}
|
||||
@@ -533,39 +516,41 @@ const ViewIOdataHeader = ({ data, isLoading }) => {
|
||||
alignItems={"start"}
|
||||
height={"95px"}
|
||||
>
|
||||
{localStorage?.getItem("role") === encryptString(import.meta.env.VITE_VITE_MAKER) && <Menu>
|
||||
<MenuButton
|
||||
className="link p-1 rounded-1 "
|
||||
bg={"#fff"}
|
||||
_hover={{ backgroundColor: "#fff !important" }}
|
||||
onClick={onOpen}
|
||||
ref={btnRef}
|
||||
>
|
||||
<HiDotsVertical className="rubix-text-dark fs-6" />
|
||||
</MenuButton>
|
||||
<MenuList fontSize={"sm"}>
|
||||
<MenuItem
|
||||
_hover={{
|
||||
bg: "#fff",
|
||||
}}
|
||||
as={"span"}
|
||||
fontWeight={600}
|
||||
className="border-bottom"
|
||||
{isMaker() && (
|
||||
<Menu>
|
||||
<MenuButton
|
||||
className="link p-1 rounded-1 "
|
||||
bg={"#fff"}
|
||||
_hover={{ backgroundColor: "#fff !important" }}
|
||||
onClick={onOpen}
|
||||
ref={btnRef}
|
||||
>
|
||||
Tansaction
|
||||
</MenuItem>
|
||||
|
||||
{filteredMenu?.map(({ id, title, onClickFunction }) => (
|
||||
<HiDotsVertical className="rubix-text-dark fs-6" />
|
||||
</MenuButton>
|
||||
<MenuList fontSize={"sm"}>
|
||||
<MenuItem
|
||||
key={id}
|
||||
onClick={onClickFunction}
|
||||
_hover={{
|
||||
bg: "#fff",
|
||||
}}
|
||||
as={"span"}
|
||||
fontWeight={600}
|
||||
className="border-bottom"
|
||||
>
|
||||
{title}
|
||||
Tansaction
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuList>
|
||||
</Menu>}
|
||||
|
||||
{filteredMenu?.map(({ id, title, onClickFunction }) => (
|
||||
<MenuItem
|
||||
key={id}
|
||||
onClick={onClickFunction}
|
||||
className="border-bottom"
|
||||
>
|
||||
{title}
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuList>
|
||||
</Menu>
|
||||
)}
|
||||
|
||||
{/* Modals */}
|
||||
<AmountInvested isOpen={isInvestmentOpen} onClose={onInvestmentClose} />
|
||||
|
||||
@@ -245,7 +245,7 @@ const Login = () => {
|
||||
)}
|
||||
</FormControl>
|
||||
<Box fontSize={"sm"} display={"flex"} justifyContent={"end"} mt={0}>
|
||||
<Text fontWeight={500} cursor={"pointer"} onClick={onOpen}>Forget Password?</Text>
|
||||
<Text fontWeight={500} cursor={"pointer"} onClick={onOpen}>Forgot Password?</Text>
|
||||
</Box>
|
||||
|
||||
<Button
|
||||
|
||||
@@ -316,7 +316,7 @@ const AddInvestmentType = () => {
|
||||
|
||||
<Box display={"flex"} justifyContent={"space-between"} alignItems={"center"} mt={5} px={4} mb={5}>
|
||||
<Text fontSize={"sm"} mb={0} onClick={() => navigate(-1)} cursor={"pointer"}>
|
||||
<ArrowBackIcon fontSize={"xl"} me={2} />Add Details
|
||||
<ArrowBackIcon fontSize={"xl"} me={2} />{params?.id ? "Edit Details" : "Add Details"}
|
||||
</Text>
|
||||
<SwitchButton isSwitchOn={isSwitchOn} setIsSwitchOn={setIsSwitchOn} />
|
||||
</Box>
|
||||
|
||||
@@ -301,7 +301,7 @@ const AddSponser = () => {
|
||||
{/* ===================== [Switch Button] ======================== */}
|
||||
<Box display={"flex"} justifyContent={"space-between"} alignItems={"center"} mt={5} px={4}>
|
||||
<Text fontSize={"sm"} mb={0} onClick={() => navigate(-1)} cursor={"pointer"}>
|
||||
<ArrowBackIcon fontSize={"xl"} me={2} />Add Details
|
||||
<ArrowBackIcon fontSize={"xl"} me={2} />{params?.id ? "Edit Details" : "Add Details"}
|
||||
</Text>
|
||||
<SwitchButton isSwitchOn={isSwitchOn} setIsSwitchOn={setIsSwitchOn} />
|
||||
</Box>
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
import { CheckIcon, CloseIcon, InfoIcon } from "@chakra-ui/icons";
|
||||
import {
|
||||
Avatar,
|
||||
Box,
|
||||
ButtonGroup,
|
||||
Editable,
|
||||
EditableInput,
|
||||
EditablePreview,
|
||||
EditableTextarea,
|
||||
Flex,
|
||||
HStack,
|
||||
Heading,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
Text,
|
||||
VStack,
|
||||
useEditableControls,
|
||||
useEditableControls
|
||||
} from "@chakra-ui/react";
|
||||
import React from "react";
|
||||
import { OPACITY_ON_LOAD } from "../../Layout/animations";
|
||||
import { CheckIcon, CloseIcon, EditIcon, InfoIcon } from "@chakra-ui/icons";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { FaEarthAmericas } from "react-icons/fa6";
|
||||
import logoMini from "../../assets/propic.png";
|
||||
import { OPACITY_ON_LOAD } from "../../Layout/animations";
|
||||
import { useAuthProfileQuery } from "../../Services/token.serivce";
|
||||
|
||||
const Profile = () => {
|
||||
/* Here's a custom control */
|
||||
@@ -53,19 +48,56 @@ const Profile = () => {
|
||||
)
|
||||
);
|
||||
}
|
||||
const { data } = useAuthProfileQuery();
|
||||
|
||||
|
||||
// Array of fields to render
|
||||
const fields = [
|
||||
{ name: "firstName", label: "First Name", defaultValue: "Faisal" },
|
||||
{ name: "lastName", label: "Last Name", defaultValue: "Aljalahma" },
|
||||
{ name: "email", label: "Email Address", defaultValue: "f.aljalahma@tanamicapital.com" },
|
||||
{ name: "mobile", label: "Mobile Number", defaultValue: "9898767876" },
|
||||
{ name: "role", label: "Role", defaultValue: "Maker" },
|
||||
];
|
||||
|
||||
|
||||
|
||||
const [fields, setFields] = useState([
|
||||
{
|
||||
name: "firstName",
|
||||
label: "First Name",
|
||||
defaultValue: null,
|
||||
},
|
||||
{
|
||||
name: "lastName",
|
||||
label: "Last Name",
|
||||
defaultValue: null,
|
||||
},
|
||||
{
|
||||
name: "email",
|
||||
label: "Email Address",
|
||||
defaultValue: null,
|
||||
},
|
||||
{
|
||||
name: "mobile",
|
||||
label: "Mobile Number",
|
||||
defaultValue: null,
|
||||
},
|
||||
{ name: "role", label: "Role", defaultValue: null },
|
||||
]);
|
||||
useEffect(() => {
|
||||
setFields([
|
||||
{
|
||||
name: "firstName",
|
||||
label: "First Name",
|
||||
defaultValue: data?.data?.firstName || null,
|
||||
},
|
||||
{
|
||||
name: "lastName",
|
||||
label: "Last Name",
|
||||
defaultValue: data?.data?.lastName || null,
|
||||
},
|
||||
{
|
||||
name: "email",
|
||||
label: "Email Address",
|
||||
defaultValue: data?.data?.emailAddress || null,
|
||||
},
|
||||
{
|
||||
name: "mobile",
|
||||
label: "Mobile Number",
|
||||
defaultValue: data?.data?.mobileNumber || null,
|
||||
},
|
||||
{ name: "role", label: "Role", defaultValue: data?.data?.role || null },
|
||||
]);
|
||||
}, [data]);
|
||||
|
||||
return (
|
||||
<VStack
|
||||
@@ -114,7 +146,7 @@ const Profile = () => {
|
||||
color={"gray.700"}
|
||||
fontWeight={500}
|
||||
>
|
||||
Faisal Aljalahma
|
||||
{data?.data?.firstName + " " + data?.data?.lastName}
|
||||
</Text>
|
||||
|
||||
<Text
|
||||
@@ -123,7 +155,7 @@ const Profile = () => {
|
||||
color={"gray.500"}
|
||||
fontWeight={400}
|
||||
>
|
||||
f.aljalahma@tanamicapital.com
|
||||
{data?.data?.emailAddress}
|
||||
</Text>
|
||||
</VStack>
|
||||
</HStack>
|
||||
@@ -150,16 +182,16 @@ const Profile = () => {
|
||||
fontWeight={500}
|
||||
>
|
||||
{" "}
|
||||
<Icon as={FaEarthAmericas} /> Maker
|
||||
<Icon as={FaEarthAmericas} /> {data?.data?.role}
|
||||
</Text>
|
||||
</VStack>
|
||||
</HStack>
|
||||
</Box>
|
||||
|
||||
{/*
|
||||
<Heading as="h3" size="sm">
|
||||
About you
|
||||
</Heading>
|
||||
|
||||
<Box
|
||||
rounded="md"
|
||||
boxShadow="base"
|
||||
@@ -170,55 +202,56 @@ const Profile = () => {
|
||||
alignItems="flex-start"
|
||||
p={6}
|
||||
gap={0}
|
||||
|
||||
pb={6}
|
||||
>
|
||||
|
||||
{fields?.map((item) => (
|
||||
<VStack alignItems={"flex-start"} w={"100%"} gap={1.5} mb={6} key={item?.label}>
|
||||
<Text
|
||||
as={"span"}
|
||||
fontSize="xs"
|
||||
fontWeight="semibold"
|
||||
color={"gray.500"}
|
||||
>
|
||||
{item?.label}
|
||||
</Text>
|
||||
<Editable
|
||||
position={"relative"}
|
||||
gap={0}
|
||||
defaultValue={item?.defaultValue}
|
||||
w="100%"
|
||||
>
|
||||
<EditablePreview
|
||||
cursor={'pointer'}
|
||||
p={2}
|
||||
rounded={"sm"}
|
||||
w={"100%"}
|
||||
_hover={{
|
||||
bg: "gray.100",
|
||||
}}
|
||||
fontSize="sm"
|
||||
transition={"0.5s"}
|
||||
/>
|
||||
<Input
|
||||
as={EditableInput}
|
||||
ps={2}
|
||||
size={'sm'}
|
||||
fontSize="sm"
|
||||
rounded={"sm"}
|
||||
_focus={{
|
||||
borderColor:"blue.500"
|
||||
}}
|
||||
/>
|
||||
<EditableControls />
|
||||
</Editable>
|
||||
</VStack>
|
||||
))}
|
||||
|
||||
|
||||
|
||||
</Box>
|
||||
{fields?.map((item) => (
|
||||
<VStack
|
||||
alignItems={"flex-start"}
|
||||
w={"100%"}
|
||||
gap={1.5}
|
||||
mb={6}
|
||||
key={item?.label}
|
||||
>
|
||||
<Text
|
||||
as={"span"}
|
||||
fontSize="xs"
|
||||
fontWeight="semibold"
|
||||
color={"gray.500"}
|
||||
>
|
||||
{item?.label}
|
||||
</Text>
|
||||
<Editable
|
||||
position={"relative"}
|
||||
gap={0}
|
||||
defaultValue={item?.defaultValue}
|
||||
w="100%"
|
||||
>
|
||||
<EditablePreview
|
||||
cursor={"pointer"}
|
||||
p={2}
|
||||
rounded={"sm"}
|
||||
w={"100%"}
|
||||
_hover={{
|
||||
bg: "gray.100",
|
||||
}}
|
||||
fontSize="sm"
|
||||
transition={"0.5s"}
|
||||
/>
|
||||
<Input
|
||||
as={EditableInput}
|
||||
ps={2}
|
||||
size={"sm"}
|
||||
fontSize="sm"
|
||||
rounded={"sm"}
|
||||
_focus={{
|
||||
borderColor: "blue.500",
|
||||
}}
|
||||
/>
|
||||
<EditableControls />
|
||||
</Editable>
|
||||
</VStack>
|
||||
))}
|
||||
</Box> */}
|
||||
</VStack>
|
||||
</VStack>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AddIcon, DeleteIcon, EditIcon } from "@chakra-ui/icons";
|
||||
import {
|
||||
Badge,
|
||||
Box,
|
||||
@@ -9,24 +10,24 @@ import {
|
||||
Tooltip,
|
||||
useToast,
|
||||
} from "@chakra-ui/react";
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import { Link, Link as RouterLink } from "react-router-dom";
|
||||
import { AddIcon, DeleteIcon, EditIcon } from "@chakra-ui/icons";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { OPACITY_ON_LOAD } from "../../Layout/animations";
|
||||
import NormalTable from "../../Components/DataTable/NormalTable";
|
||||
import Pagination from "../../Components/Pagination";
|
||||
import GlobalStateContext from "../../Contexts/GlobalStateContext";
|
||||
import React, { useContext, useState } from "react";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import CustomAlertDialog from "../../Components/CustomAlertDialog";
|
||||
import NormalTable from "../../Components/DataTable/NormalTable";
|
||||
import ToastBox from "../../Components/ToastBox";
|
||||
import { TABLE_PAGINATION } from "../../Constants/Paginations";
|
||||
import { generateSerialNumber } from "../../Constants/Constants";
|
||||
import { useGetSponserMasterQuery } from "../../Services/io.service";
|
||||
import {
|
||||
CHECKER_ID,
|
||||
generateSerialNumber,
|
||||
MAKER_ID,
|
||||
SUPER_ADMIN_ID,
|
||||
} from "../../Constants/Constants";
|
||||
import GlobalStateContext from "../../Contexts/GlobalStateContext";
|
||||
import { OPACITY_ON_LOAD } from "../../Layout/animations";
|
||||
import {
|
||||
useDeleteUserMutation,
|
||||
useGetSubAdminMasterQuery,
|
||||
useToggleStatusMutation,
|
||||
} from "../../Services/subadmin.service";
|
||||
import RoleSwitchButton from "../../Components/RoleSwitchButton";
|
||||
|
||||
export const formatDate = (date) => {
|
||||
const d = new Date(date);
|
||||
@@ -46,31 +47,28 @@ const SubAdmin = () => {
|
||||
const [mouseEntered, setMouseEntered] = useState(false);
|
||||
const [mouseEnteredId, setMouseEnteredId] = useState("");
|
||||
// const [deleteSponser] = useDeleteSponserMutation();
|
||||
const { sponser, setSponser, slideFromRight } =
|
||||
useContext(GlobalStateContext);
|
||||
const { slideFromRight } = useContext(GlobalStateContext);
|
||||
|
||||
// =========================== [Use State] =============================
|
||||
const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
|
||||
const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
|
||||
// const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
|
||||
// const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
|
||||
const [isSwitchOn, setIsSwitchOn] = useState(true);
|
||||
// const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
|
||||
|
||||
// Debounce the search term to avoid making a request on every keystroke
|
||||
useEffect(() => {
|
||||
const handler = setTimeout(() => {
|
||||
setDebouncedSearchTerm(searchTerm);
|
||||
}, 500); // Adjust delay as needed
|
||||
return () => {
|
||||
clearTimeout(handler);
|
||||
};
|
||||
}, [searchTerm]);
|
||||
// useEffect(() => {
|
||||
// const handler = setTimeout(() => {
|
||||
// setDebouncedSearchTerm(searchTerm);
|
||||
// }, 500); // Adjust delay as needed
|
||||
// return () => {
|
||||
// clearTimeout(handler);
|
||||
// };
|
||||
// }, [searchTerm]);
|
||||
|
||||
const {
|
||||
data: subAdmin,
|
||||
error,
|
||||
isLoading: isSponserLoading,
|
||||
} = useGetSubAdminMasterQuery();
|
||||
const { data: subAdmin, isLoading: isSponserLoading } =
|
||||
useGetSubAdminMasterQuery();
|
||||
|
||||
const [deleteUser] = useDeleteUserMutation();
|
||||
|
||||
const [toggleStatus] = useToggleStatusMutation();
|
||||
|
||||
@@ -91,13 +89,13 @@ const SubAdmin = () => {
|
||||
});
|
||||
|
||||
const handleToggleStatus = async (isMaker, id) => {
|
||||
console.log("hit");
|
||||
// console.log("hit");
|
||||
const data = {
|
||||
role_xid: isMaker ? "2" : "1",
|
||||
role_xid: isMaker ? CHECKER_ID : MAKER_ID,
|
||||
};
|
||||
console.log("=======================",data)
|
||||
console.log("=======================", data);
|
||||
try {
|
||||
const res = await toggleStatus({id, data});
|
||||
const res = await toggleStatus({ id, data });
|
||||
if (res?.error) {
|
||||
toast({
|
||||
render: () => (
|
||||
@@ -137,7 +135,7 @@ const SubAdmin = () => {
|
||||
"Action",
|
||||
];
|
||||
|
||||
const extractedArray = subAdmin?.data?.map((item, index) => ({
|
||||
const extractedArray = filteredData?.map((item, index) => ({
|
||||
"Sr No": (
|
||||
<Text
|
||||
w={"24px"}
|
||||
@@ -147,7 +145,7 @@ const SubAdmin = () => {
|
||||
className="d-flex align-items-center fw-bold web-text-small"
|
||||
>
|
||||
{/* {item.id} */}
|
||||
{generateSerialNumber(index, currentPage, pageSize)}
|
||||
{generateSerialNumber(index)}
|
||||
</Text>
|
||||
),
|
||||
"First Name": (
|
||||
@@ -180,17 +178,17 @@ const SubAdmin = () => {
|
||||
</Box>
|
||||
),
|
||||
Role: (
|
||||
<Box isTruncated={true} >
|
||||
<Box isTruncated={true}>
|
||||
<Badge
|
||||
py={"2px"}
|
||||
me={2}
|
||||
fontWeight={600}
|
||||
bg={item?.role[0]?.role === "Maker" ? "#00ffcc" : "#b3ff99"}
|
||||
px={item?.role[0]?.role === "Maker" ? "12px" : "5px"}
|
||||
px={item?.role[0]?.role === "Maker" ? "12px" : "5px"}
|
||||
>
|
||||
{item?.role[0]?.role}
|
||||
</Badge>
|
||||
<Switch
|
||||
{/* <Switch
|
||||
onChange={() =>
|
||||
handleToggleStatus(item?.role[0]?.role === "Maker", item?.id)
|
||||
}
|
||||
@@ -201,7 +199,7 @@ const SubAdmin = () => {
|
||||
bg: item?.role[0]?.role === "Maker" ? "#00ffcc" : "#b3ff99", // "Off" state color
|
||||
},
|
||||
}}
|
||||
/>
|
||||
/> */}
|
||||
{/* <RoleSwitchButton
|
||||
setIsSwitchOn={setIsSwitchOn}
|
||||
isSwitchOn={item?.role[0]?.role === "Maker"}
|
||||
@@ -231,7 +229,7 @@ const SubAdmin = () => {
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
{/* <Tooltip
|
||||
<Tooltip
|
||||
rounded={"sm"}
|
||||
fontSize={"xs"}
|
||||
label="Delete"
|
||||
@@ -240,12 +238,14 @@ const SubAdmin = () => {
|
||||
placement="top"
|
||||
>
|
||||
<Button
|
||||
isDisabled={item?.id === SUPER_ADMIN_ID}
|
||||
onClick={() => {
|
||||
setActionId(item?.id);
|
||||
setDeleteAlert(true);
|
||||
}}
|
||||
// _hover={{ color: "red.500" }}
|
||||
// color="red"
|
||||
// disabled={true}
|
||||
rounded={"sm"}
|
||||
size={"xs"}
|
||||
colorScheme="red"
|
||||
@@ -253,46 +253,42 @@ const SubAdmin = () => {
|
||||
>
|
||||
<DeleteIcon />
|
||||
</Button>
|
||||
</Tooltip> */}
|
||||
</Tooltip>
|
||||
</Box>
|
||||
),
|
||||
}));
|
||||
|
||||
// =========================== [ Delete Function ] =================================
|
||||
|
||||
// const handleDelete = async () => {
|
||||
// console.log(actionId);
|
||||
// setIsLoading(true);
|
||||
// try {
|
||||
// const response = await deleteSponser(actionId);
|
||||
// console.log(response?.data);
|
||||
// if (response?.error?.data?.code === 400) {
|
||||
// toast({
|
||||
// render: () => (
|
||||
// <ToastBox
|
||||
// message={response?.error?.data?.message}
|
||||
// status={"error"}
|
||||
// />
|
||||
// ),
|
||||
// });
|
||||
// setIsLoading(false);
|
||||
// setDeleteAlert(false);
|
||||
// } else if (
|
||||
// response?.data?.statusCode === 201 ||
|
||||
// response?.data?.statusCode === 200
|
||||
// ) {
|
||||
// toast({
|
||||
// render: () => (
|
||||
// <ToastBox message={response?.data?.message} status={"success"} />
|
||||
// ),
|
||||
// });
|
||||
// setIsLoading(false);
|
||||
// setDeleteAlert(false);
|
||||
// }
|
||||
// } catch (error) {}
|
||||
// };
|
||||
|
||||
console.log(isSponserLoading);
|
||||
const handleDelete = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await deleteUser(actionId);
|
||||
if (response?.error?.data?.code === 400) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox
|
||||
message={response?.error?.data?.message}
|
||||
status={"error"}
|
||||
/>
|
||||
),
|
||||
});
|
||||
setIsLoading(false);
|
||||
setDeleteAlert(false);
|
||||
} else if (
|
||||
response?.data?.statusCode === 201 ||
|
||||
response?.data?.statusCode === 200
|
||||
) {
|
||||
toast({
|
||||
render: () => (
|
||||
<ToastBox message={response?.data?.message} status={"success"} />
|
||||
),
|
||||
});
|
||||
setIsLoading(false);
|
||||
setDeleteAlert(false);
|
||||
}
|
||||
} catch (error) {}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={38}>
|
||||
@@ -322,14 +318,14 @@ const SubAdmin = () => {
|
||||
<HStack display={"flex"} alignItems={"center"}>
|
||||
{/* ====================[Pagination]===================== */}
|
||||
|
||||
<Pagination
|
||||
{/* <Pagination
|
||||
isLoading={isSponserLoading}
|
||||
pageSize={pageSize}
|
||||
setPageSize={setPageSize}
|
||||
currentPage={currentPage}
|
||||
setCurrentPage={setCurrentPage}
|
||||
totalItems={subAdmin?.data?.totalItems}
|
||||
/>
|
||||
/> */}
|
||||
|
||||
{/* =====================[Add Button]===================== */}
|
||||
|
||||
@@ -366,8 +362,8 @@ const SubAdmin = () => {
|
||||
<CustomAlertDialog
|
||||
onClose={() => setDeleteAlert(false)}
|
||||
isOpen={deleteAlert}
|
||||
message={"Are you sure you want to delete sponers?"}
|
||||
// alertHandler={handleDelete}
|
||||
message={"Are you sure you want to delete sub-admin?"}
|
||||
alertHandler={handleDelete}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
@@ -1,42 +1,42 @@
|
||||
import React, { useContext, useEffect, useState } from "react";
|
||||
import { Box, Button, Text, useToast } from "@chakra-ui/react";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import * as yup from "yup";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { ArrowBackIcon } from "@chakra-ui/icons";
|
||||
import { OPACITY_ON_LOAD } from "../../Layout/animations";
|
||||
import FormInputMain from "../../Components/FormInputMain";
|
||||
import ToastBox from "../../Components/ToastBox";
|
||||
import FullscreenLoaders from "../../Components/Loaders/FullscreenLoaders";
|
||||
import { Box, Text, useToast } from "@chakra-ui/react";
|
||||
import { yupResolver } from "@hookform/resolvers/yup";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import * as yup from "yup";
|
||||
import CustomAlertDialog from "../../Components/CustomAlertDialog";
|
||||
import FormInputMain from "../../Components/FormInputMain";
|
||||
import FullscreenLoaders from "../../Components/Loaders/FullscreenLoaders";
|
||||
import RoleSwitchButton from "../../Components/RoleSwitchButton";
|
||||
import ToastBox from "../../Components/ToastBox";
|
||||
import {
|
||||
isMaker
|
||||
} from "../../Constants/Constants";
|
||||
import { OPACITY_ON_LOAD } from "../../Layout/animations";
|
||||
import {
|
||||
useCreateSubAdminMutation,
|
||||
useGetSubAdminByIdQuery,
|
||||
useUpdateSubAdminMutation,
|
||||
} from "../../Services/subadmin.service";
|
||||
import { useGetSponserByIdQuery } from "../../Services/io.service";
|
||||
import { encryptString } from "../../Constants/Constants";
|
||||
// ======================= [validation] =========================
|
||||
|
||||
export const addSubAdmin = yup.object().shape({
|
||||
const addSubAdminSchema = yup.object().shape({
|
||||
firstName: yup
|
||||
.string()
|
||||
.required("First Name is required")
|
||||
.min(3, "First Name must be at least 3 characters long")
|
||||
.max(50, "First Name cannot exceed 50 characters")
|
||||
.max(35, "First Name cannot exceed 35 characters")
|
||||
.matches(/^[^\d]+$/, "First Name cannot contain numbers"),
|
||||
|
||||
lastName: yup.string().required("Last Name name in arabic is required"),
|
||||
emailAddress: yup.string().email("Invalid email address").notRequired(),
|
||||
// .test("emailValidity", "Email address is invalid", async function (value) {
|
||||
// if (!value) {
|
||||
// return true; // Allow if the field is empty
|
||||
// }
|
||||
// return await checkEmailValidity(value);
|
||||
// }),
|
||||
lastName: yup.string().required("Last Name is required")
|
||||
.min(3, "Last Name must be at least 3 characters long")
|
||||
.max(35, "Last Name cannot exceed 35 characters")
|
||||
.matches(/^[^\d]+$/, "Last Name cannot contain numbers"),
|
||||
emailAddress:yup.
|
||||
string()
|
||||
.required("Email address is required")
|
||||
.min(6, "Email address must be at least 6 characters long")
|
||||
.max(255, "Email address can be at most 255 characters long"),
|
||||
});
|
||||
|
||||
// ==================== [debounce] ========================
|
||||
@@ -60,17 +60,15 @@ const SubAdminUpdateCreate = () => {
|
||||
const [isLoadingBtn, setIsLoadingBtn] = useState(false);
|
||||
const [alert, setAlert] = useState(false);
|
||||
const [form, setForm] = useState();
|
||||
const [isSwitchOn, setIsSwitchOn] = useState(true);
|
||||
const [isSwitchOn, setIsSwitchOn] = useState(false);
|
||||
|
||||
const [createSubAdmin] = useCreateSubAdminMutation();
|
||||
const [updateSubAdmin] = useUpdateSubAdminMutation();
|
||||
|
||||
// Fetch sponsor data only if id exists
|
||||
const {
|
||||
data: subAdminByIdData,
|
||||
error,
|
||||
isLoading,
|
||||
} = useGetSubAdminByIdQuery(id, { skip: !id });
|
||||
const { data: subAdminByIdData, isLoading } = useGetSubAdminByIdQuery(id, {
|
||||
skip: !id,
|
||||
});
|
||||
|
||||
// ======================== [validators] ===========================
|
||||
|
||||
@@ -81,7 +79,8 @@ const SubAdminUpdateCreate = () => {
|
||||
formState: { errors },
|
||||
reset,
|
||||
} = useForm({
|
||||
resolver: yupResolver(addSubAdmin),
|
||||
resolver: yupResolver(addSubAdminSchema),
|
||||
mode: "all",
|
||||
});
|
||||
|
||||
// ========================== [useEffect] ================================
|
||||
@@ -93,15 +92,11 @@ const SubAdminUpdateCreate = () => {
|
||||
lastName: subAdminByIdData?.data?.lastName,
|
||||
emailAddress: subAdminByIdData?.data?.emailAddress,
|
||||
});
|
||||
setIsSwitchOn(
|
||||
subAdminByIdData?.data?.role[0]?.role ===
|
||||
encryptString(import.meta.env.VITE_VITE_MAKER)
|
||||
);
|
||||
console.log(subAdminByIdData?.data?.role);
|
||||
setIsSwitchOn(isMaker(subAdminByIdData?.data?.role[0]?.role));
|
||||
}
|
||||
}, [subAdminByIdData, reset]);
|
||||
|
||||
if (false) {
|
||||
if (isLoading) {
|
||||
return <FullscreenLoaders />;
|
||||
}
|
||||
|
||||
@@ -116,7 +111,7 @@ const SubAdminUpdateCreate = () => {
|
||||
try {
|
||||
const formData = {
|
||||
...form,
|
||||
// role_xid: !isSwitchOn ? 1 : 2,
|
||||
role_xid: !isSwitchOn ? 2 : 1,
|
||||
};
|
||||
await updateSubAdmin({ data: formData, id }).then((response) => {
|
||||
if (response?.data?.statusCode) {
|
||||
@@ -194,8 +189,8 @@ const SubAdminUpdateCreate = () => {
|
||||
type: "text",
|
||||
isRequired: true,
|
||||
section: "",
|
||||
maxLength: 50,
|
||||
helperText: `Maximum length should be 50 characters. You have entered ${
|
||||
maxLength: 35,
|
||||
helperText: `Maximum length should be 35 characters. You have entered ${
|
||||
watch()?.firstName?.length || 0
|
||||
} characters.`,
|
||||
},
|
||||
@@ -206,8 +201,8 @@ const SubAdminUpdateCreate = () => {
|
||||
type: "text",
|
||||
isRequired: true,
|
||||
section: "",
|
||||
maxLength: 55,
|
||||
helperText: `Maximum length should be 55 characters. You have entered ${
|
||||
maxLength: 35,
|
||||
helperText: `Maximum length should be 35 characters. You have entered ${
|
||||
watch()?.lastName?.length || 0
|
||||
} characters.`,
|
||||
},
|
||||
@@ -216,7 +211,7 @@ const SubAdminUpdateCreate = () => {
|
||||
name: "emailAddress",
|
||||
placeHolder: " ",
|
||||
type: "email",
|
||||
// isRequired: true,
|
||||
isRequired: true,
|
||||
section: "",
|
||||
},
|
||||
];
|
||||
@@ -231,8 +226,8 @@ const SubAdminUpdateCreate = () => {
|
||||
type: "text",
|
||||
isRequired: true,
|
||||
section: "",
|
||||
maxLength: 55,
|
||||
helperText: `Maximum length should be 55 characters. You have entered ${
|
||||
maxLength: 35,
|
||||
helperText: `Maximum length should be 35 characters. You have entered ${
|
||||
watch()?.firstName?.length || 0
|
||||
} characters.`,
|
||||
},
|
||||
@@ -243,8 +238,8 @@ const SubAdminUpdateCreate = () => {
|
||||
type: "text",
|
||||
isRequired: true,
|
||||
section: "",
|
||||
maxLength: 55,
|
||||
helperText: `Maximum length should be 55 characters. You have entered ${
|
||||
maxLength: 35,
|
||||
helperText: `Maximum length should be 35 characters. You have entered ${
|
||||
watch()?.lastName?.length || 0
|
||||
} characters.`,
|
||||
},
|
||||
@@ -253,7 +248,7 @@ const SubAdminUpdateCreate = () => {
|
||||
name: "emailAddress",
|
||||
placeHolder: " ",
|
||||
type: "email",
|
||||
// isRequired: true,
|
||||
isRequired: true,
|
||||
section: "",
|
||||
},
|
||||
];
|
||||
@@ -281,7 +276,7 @@ const SubAdminUpdateCreate = () => {
|
||||
}, {});
|
||||
|
||||
// ==================== [On Submit] ========================
|
||||
console.log(errors);
|
||||
// console.log(errors);
|
||||
|
||||
const onSubmit = async (data) => {
|
||||
console.log("Hit");
|
||||
@@ -311,16 +306,20 @@ const SubAdminUpdateCreate = () => {
|
||||
cursor={"pointer"}
|
||||
>
|
||||
<ArrowBackIcon fontSize={"xl"} me={2} />
|
||||
Add Details
|
||||
{params?.id ? "Edit Details" : "Add Details"}
|
||||
</Text>
|
||||
{params?.id ? (
|
||||
{/* {params?.id ? (
|
||||
""
|
||||
) : (
|
||||
<RoleSwitchButton
|
||||
isSwitchOn={isSwitchOn}
|
||||
setIsSwitchOn={setIsSwitchOn}
|
||||
/>
|
||||
)}
|
||||
)} */}
|
||||
<RoleSwitchButton
|
||||
isSwitchOn={isSwitchOn}
|
||||
setIsSwitchOn={setIsSwitchOn}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{/* ====================== [Form Input] ====================== */}
|
||||
|
||||
@@ -421,7 +421,7 @@ export const ioService = createApi({
|
||||
}),
|
||||
|
||||
profile: builder.query({
|
||||
query: (id) => `/auth/admin/profile`,
|
||||
query: () => `/auth/admin/profile`,
|
||||
}),
|
||||
|
||||
// ========Add Io Details========
|
||||
@@ -435,7 +435,7 @@ export const ioService = createApi({
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
|
||||
|
||||
updateTransaction: builder.mutation({
|
||||
query: (id) => ({
|
||||
// url: `/io/admin/maker-transaction/${id}/verify-pending-transaction-for-cash-and-nav`,
|
||||
@@ -448,45 +448,45 @@ export const ioService = createApi({
|
||||
|
||||
|
||||
addNavDetails: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/maker-transaction/${id}/io-nav`,
|
||||
method: "POST",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
addIOTransaction: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/maker-transaction/${id}/io-nav`,
|
||||
method: "POST",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
saveIOTransaction: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/maker-transaction/${id}/io-yeild`,
|
||||
method: "POST",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
exitIOTransaction: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/maker-transaction/${id}/io-exit`,
|
||||
method: "POST",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
|
||||
|
||||
addIoCase: builder.mutation({
|
||||
query: (id) => ({
|
||||
@@ -499,10 +499,10 @@ export const ioService = createApi({
|
||||
|
||||
|
||||
approveIOCase: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/io-cash/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
@@ -510,71 +510,71 @@ export const ioService = createApi({
|
||||
|
||||
|
||||
approveIONav: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/io-nav/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
approveDistribution: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/distributed-to-investor/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
|
||||
|
||||
approveExit: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/exit/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
approveInvested: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/amount-invested/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
|
||||
approveDistributed: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/distributed-to-investor/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
approveExitTransaction: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/exit/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
approveCancleTransaction: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/approved/cancel/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
@@ -582,16 +582,16 @@ export const ioService = createApi({
|
||||
|
||||
|
||||
rejectIOCase: builder.mutation({
|
||||
query: ({id,data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/io/admin/checker-transaction/reject/${id}`,
|
||||
method: "PATCH",
|
||||
body:data,
|
||||
body: data,
|
||||
}),
|
||||
|
||||
invalidatesTags: ["getIOById"],
|
||||
}),
|
||||
|
||||
|
||||
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { baseQuery } from "./token.serivce";
|
||||
export const sabAdminMaster = createApi({
|
||||
reducerPath: "sabAdminMaster",
|
||||
baseQuery: baseQuery,
|
||||
tagTypes: ["getSubAdmin", "prePopulate"],
|
||||
tagTypes: ["getSubAdmin", "prePopulate","getSubAdminById"],
|
||||
endpoints: (builder) => ({
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ export const sabAdminMaster = createApi({
|
||||
method: "POST",
|
||||
body: data,
|
||||
}),
|
||||
invalidatesTags: ["getSubAdmin","prePopulate"],
|
||||
invalidatesTags: ["getSubAdmin", "prePopulate"],
|
||||
}),
|
||||
|
||||
// // ========[Update Sponser]========
|
||||
@@ -40,17 +40,18 @@ export const sabAdminMaster = createApi({
|
||||
method: "PATCH",
|
||||
body: data,
|
||||
}),
|
||||
invalidatesTags: ["getSubAdmin"],
|
||||
invalidatesTags: ["getSubAdmin","getSubAdminById"],
|
||||
}),
|
||||
|
||||
getSubAdminById: builder.query({
|
||||
query: (id) => `/subadmin/admin/${id}`,
|
||||
providesTags: ["getSubAdminById"],
|
||||
}),
|
||||
|
||||
// // ========[Toggle Status]========
|
||||
|
||||
toggleStatus: builder.mutation({
|
||||
query: ({id, data}) => ({
|
||||
query: ({ id, data }) => ({
|
||||
url: `/subadmin/admin/toggle-role/${id}`,
|
||||
method: "PATCH",
|
||||
body: data,
|
||||
@@ -58,41 +59,26 @@ export const sabAdminMaster = createApi({
|
||||
invalidatesTags: ["getSubAdmin"],
|
||||
}),
|
||||
|
||||
// // ========[Get Active]========
|
||||
|
||||
// getActiveSponserMaster: builder.query({
|
||||
// query: () => `/sponsor/admin/active`,
|
||||
// }),
|
||||
|
||||
// getSponserMasterActive: builder.query({
|
||||
// query: () => "/sponsor/admin/active",
|
||||
// }),
|
||||
|
||||
// // ======[Get ID]=====
|
||||
|
||||
// getSponserById: builder.query({
|
||||
// query: (id) => `/sponsor/admin/${id}`,
|
||||
// }),
|
||||
|
||||
// // ========[Update Sponser]========
|
||||
|
||||
// updateSponser: builder.mutation({
|
||||
// query: ({ data, id }) => ({
|
||||
// url: `/sponsor/admin/${id}`,
|
||||
// method: "PATCH",
|
||||
// body: data,
|
||||
// }),
|
||||
// invalidatesTags: ["getSponser"],
|
||||
// }),
|
||||
// ==========[Delete User] ==========
|
||||
deleteUser: builder.mutation({
|
||||
query: (id) => ({
|
||||
url: `/subadmin/admin/${id}`,
|
||||
method: "DELETE",
|
||||
}),
|
||||
invalidatesTags: ["getSubAdmin"],
|
||||
}),
|
||||
|
||||
|
||||
}),
|
||||
});
|
||||
|
||||
// Export hooks for usage in functional components
|
||||
export const {
|
||||
useGetSubAdminMasterQuery,
|
||||
useCreateSubAdminMutation,
|
||||
useUpdateSubAdminMutation,
|
||||
useGetSubAdminByIdQuery,
|
||||
useToggleStatusMutation
|
||||
useGetSubAdminMasterQuery,
|
||||
useCreateSubAdminMutation,
|
||||
useUpdateSubAdminMutation,
|
||||
useGetSubAdminByIdQuery,
|
||||
useToggleStatusMutation,
|
||||
useDeleteUserMutation,
|
||||
} = sabAdminMaster;
|
||||
|
||||
@@ -1,132 +1,122 @@
|
||||
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
|
||||
import { encryptString } from '../Constants/Constants'
|
||||
|
||||
// Define a base query function with RTK Query
|
||||
// export const baseQuery = fetchBaseQuery({
|
||||
// baseUrl: 'https://sprint4.tanami.betadelivery.com/api/v1',
|
||||
// prepareHeaders: (headers) => {
|
||||
// const token = localStorage.getItem('accessToken');
|
||||
// if (token) {
|
||||
// headers.set('x-auth-token', `${token}`);
|
||||
// }
|
||||
// return headers;
|
||||
// },
|
||||
// });
|
||||
|
||||
// Define a base query function with token refresh logic
|
||||
// Define a base query function with token refresh logic, retry mechanism, and AbortController
|
||||
export const baseQuery = async (args, api, extraOptions) => {
|
||||
let result = await fetchBaseQuery({
|
||||
baseUrl: import.meta.env.VITE_BAS_URL,
|
||||
prepareHeaders: (headers) => {
|
||||
const token = localStorage.getItem("accessToken");
|
||||
if (token) {
|
||||
headers.set("x-auth-token", token);
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
})(args, api, extraOptions);
|
||||
const fetchBase = fetchBaseQuery({
|
||||
baseUrl: import.meta.env.VITE_BAS_URL,
|
||||
credentials: 'include',
|
||||
prepareHeaders: (headers) => {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
return headers;
|
||||
},
|
||||
});
|
||||
|
||||
if (result.error && result.error.status === 403) {
|
||||
// Handle token refresh
|
||||
const refreshToken = localStorage.getItem("refreshToken");
|
||||
console.log(refreshToken);
|
||||
if (refreshToken) {
|
||||
try {
|
||||
const refreshResult = await fetchBaseQuery({
|
||||
baseUrl: import.meta.env.VITE_BAS_URL,
|
||||
})(
|
||||
{
|
||||
url: "/auth/user/regenerate-token",
|
||||
method: "POST",
|
||||
body: { refreshToken },
|
||||
},
|
||||
api,
|
||||
extraOptions
|
||||
);
|
||||
const abortController = new AbortController();
|
||||
extraOptions = {
|
||||
...extraOptions,
|
||||
signal: abortController.signal,
|
||||
};
|
||||
|
||||
if (refreshResult.data) {
|
||||
// Save new tokens
|
||||
localStorage.setItem("accessToken", refreshResult?.data?.data?.access?.token);
|
||||
// localStorage.setItem("role", refreshResult?.data?.data?.role);
|
||||
// console.log(refreshResult?.data?.data?.role);
|
||||
|
||||
let result = await fetchBase(args, api, extraOptions);
|
||||
|
||||
// Retry the original request with the new token
|
||||
result = await fetchBaseQuery({
|
||||
baseUrl: import.meta.env.VITE_BAS_URL,
|
||||
prepareHeaders: (headers) => {
|
||||
const token = localStorage.getItem("accessToken");
|
||||
if (token) {
|
||||
headers.set("x-auth-token", token);
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
})(args, api, extraOptions);
|
||||
}else{
|
||||
if (result.error) {
|
||||
if (result.error.status === 403) {
|
||||
let retryCount = 0;
|
||||
const maxRetries = import.meta.env.VITE_MAX_TRY_REGENRATE_TOKEN || 2;
|
||||
|
||||
console.log('refresh failed');
|
||||
localStorage.clear();
|
||||
window.location.href = '/login'; // Redirect to login page
|
||||
while (retryCount < maxRetries) {
|
||||
try {
|
||||
const { data, error } = await fetchBase(
|
||||
{
|
||||
url: "/auth/user/regenerate-token",
|
||||
method: "POST",
|
||||
},
|
||||
api,
|
||||
{ ...extraOptions, signal: abortController.signal }
|
||||
);
|
||||
if (data) {
|
||||
// Retry the original query after successful token regeneration
|
||||
return await fetchBase(args, api, { ...extraOptions, signal: abortController.signal });
|
||||
}
|
||||
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to refresh token:", err);
|
||||
localStorage.clear();
|
||||
window.location.href = '/login'; // Redirect to login page
|
||||
// Handle refresh failure (e.g., redirect to login)
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} catch (err) {
|
||||
retryCount++;
|
||||
if (retryCount >= maxRetries) {
|
||||
console.error("Failed to refresh token after retries:", err);
|
||||
abortController.abort();
|
||||
localStorage.clear();
|
||||
window.location.href = '/login'; // Redirect to login page
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (result.error.status === 401) {
|
||||
abortController.abort();
|
||||
localStorage.clear();
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
return result;
|
||||
};
|
||||
|
||||
// Create an RTK Query API slice
|
||||
export const apiSlice = createApi({
|
||||
reducerPath: "api",
|
||||
baseQuery: baseQuery,
|
||||
endpoints: (builder) => ({
|
||||
login: builder.mutation({
|
||||
query: (credentials) => ({
|
||||
url: "/auth/admin",
|
||||
method: "POST",
|
||||
body: credentials,
|
||||
}),
|
||||
async onQueryStarted(arg, { dispatch, queryFulfilled }) {
|
||||
try {
|
||||
const { data } = await queryFulfilled;
|
||||
// Store tokens in local storage
|
||||
localStorage.setItem("accessToken", data?.data?.access?.token);
|
||||
|
||||
localStorage.setItem("refreshToken", data?.data?.refresh?.token);
|
||||
// localStorage.setItem('refreshTokenExp', data?.data?.refresh?.expires);
|
||||
localStorage.setItem("accessTokenExp", data?.data?.access?.expires);
|
||||
localStorage.setItem("role", encryptString(data?.data?.role));
|
||||
} catch (error) {
|
||||
console.error("Login failed:", error);
|
||||
}
|
||||
},
|
||||
}),
|
||||
refreshToken: builder.mutation({
|
||||
query: (refreshToken) => ({
|
||||
url: "/auth/user/regenerate-token",
|
||||
method: "POST",
|
||||
body: { refreshToken },
|
||||
}),
|
||||
}),
|
||||
reducerPath: "api",
|
||||
baseQuery: baseQuery,
|
||||
tagTypes: ["authProfile"],
|
||||
endpoints: (builder) => ({
|
||||
|
||||
login: builder.mutation({
|
||||
query: (credentials) => ({
|
||||
url: "/auth/admin",
|
||||
method: "POST",
|
||||
body: credentials,
|
||||
}),
|
||||
async onQueryStarted(arg, { queryFulfilled }) {
|
||||
try {
|
||||
const { data } = await queryFulfilled;
|
||||
localStorage.setItem("role", encryptString(data?.data?.role));
|
||||
} catch (error) {
|
||||
console.error("Login failed:", error);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
refreshToken: builder.mutation({
|
||||
query: (refreshToken) => ({
|
||||
url: "/auth/user/regenerate-token",
|
||||
method: "POST",
|
||||
body: { refreshToken },
|
||||
}),
|
||||
}),
|
||||
|
||||
logout: builder.mutation({
|
||||
query: () => ({
|
||||
url: "/auth/admin/logout",
|
||||
method: "POST",
|
||||
}),
|
||||
}),
|
||||
|
||||
authProfile: builder.query({
|
||||
query: () => `/auth/admin/profile`,
|
||||
providesTags: (result) => result ? [{ type: 'Auth', id: 'profile' }] : [],
|
||||
onQueryStarted: async (args, { queryFulfilled }) => {
|
||||
try {
|
||||
const { data } = await queryFulfilled; // Get the data from the query response
|
||||
if (data?.role) {
|
||||
localStorage.setItem('role', encryptString(data.role));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error setting role in localStorage:', error);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
|
||||
logout: builder.mutation({
|
||||
query: () => ({
|
||||
url: "/auth/admin/logout",
|
||||
method: "POST",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}),
|
||||
});
|
||||
|
||||
export const { useLoginMutation, useRefreshTokenMutation, useLogoutMutation } = apiSlice;
|
||||
export const { useLoginMutation, useRefreshTokenMutation, useLogoutMutation, useAuthProfileQuery } = apiSlice;
|
||||
|
||||
Reference in New Issue
Block a user