Merge pull request 'transfer' (#1) from transfer into development

Reviewed-on: https://git.humbingo.in/ResearchAndDevelopment/timetracking-fe/pulls/1
master
Jay Patel 2024-08-21 07:23:37 +00:00
commit c5d600b60e
53 changed files with 4223 additions and 313 deletions

139
.gitignore vendored
View File

@ -1,132 +1,23 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# dependencies
/node_modules
/.pnp
.pnp.js
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# testing
/coverage
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# production
/build
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1,2 +1,70 @@
# timetracking-fe
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,25 @@
{
"name": "ticketmanager-fe",
"name": "hbaseapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.13.0",
"@emotion/styled": "^11.13.0",
"@fortawesome/free-solid-svg-icons": "^6.6.0",
"@fortawesome/react-fontawesome": "^0.2.2",
"@mui/icons-material": "^5.16.7",
"@mui/material": "^5.16.7",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.4",
"jwt-decode": "^4.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router": "^6.26.1",
"react-router-dom": "^6.26.1",
"react-scripts": "5.0.1",
"react-toastify": "^10.0.5",
"web-vitals": "^2.1.4"
},
"scripts": {

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

26
src/App.js Normal file
View File

@ -0,0 +1,26 @@
import React from 'react';
import LoginPage from './pages/UI/login/login';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { AuthProvider } from './auth/AuthContext';
import { Auth } from './auth/auth';
import Footer from './components/footer'; // Import the Footer component
import Home from './pages/UI/home/home';
const App = () => {
return (
<div className='App' style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/" element={<Auth component={<Home />} />} exact />
<Route path="/login" element={<Auth component={<LoginPage />} />} exact />
</Routes>
<Footer />
</AuthProvider>
</BrowserRouter>
</div>
);
};
export default App;

View File

@ -0,0 +1,416 @@
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Swal from "sweetalert2";
import "./style.css";
import useAPIManager from "./useAPIManager";
import {
Button,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
Menu,
MenuItem,
Fade,
Card,
CardContent,
} from "@mui/material";
import FormWithDrawer from "./FormWithDrawer";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import Pagination from "./Pagination";
function APIManager(props) {
const dataSchema = props.data;
const { Get, Delete, Patch, getAPI, getHost } = useAPIManager(
props.globalConfig,
props.token
);
const dataApi = getAPI(props.data.api);
const [apiData, setApiData] = useState([]);
const [searchQuery, setSearchQuery] = useState("");
const [orderBy, setOrderBy] = useState(""); // Column to sort
const [order, setOrder] = useState("asc");
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(50);
const [sortedColumn, setSortedColumn] = useState(null);
const [filteredData, setFilteredData] = useState([]);
const [anchorEls, setAnchorEls] = useState({}); // Updated state for menu anchors
const [mounted, setMounted] = useState(false);
const [nextPage, setNextPage] = useState(null);
const [previousPage, setPreviousPage] = useState(null);
const [totalCount, setTotalCount] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [loading, setLoading] = useState(true);
const updateFormTitle = props.updateFormTitle ? props.updateFormTitle : "";
const createFormTitle = props.createFormTitle ? props.createFormTitle : "";
const actionBtnName = props.actionBtnName
? props.actionBtnName
: "Create New Data";
const createRequired = props.createRequired === false ? false : true;
const editRequired = props.editRequired === false ? false : true;
const searchRequired = props.searchRequired === false ? false : true;
const createField = dataSchema.createField;
const editField = dataSchema.editField;
const showField = dataSchema.showField;
const manageRecord = true;
let navigate = useNavigate();
const getData = async () => {
makeApiRequest(dataApi);
};
const makeApiRequest = async (api) => {
try {
setSearchQuery("");
const result = await Get(api ? api : dataApi);
setNextPage(result.next);
setPreviousPage(result.previous);
setTotalCount(result.count);
setApiData(result.results);
setFilteredData(result.results);
} catch (err) {
if (err.code == "ERR_BAD_REQUEST") {
toast.error("Unauthorised access to page, Contact admin for access.");
navigate("/");
} else {
toast.error(err.message);
}
} finally {
setLoading(false);
}
};
const pageChangeRequest = (url) => {
if (getPageUrl(url) != null) {
makeApiRequest(getHost() + getPageUrl(url));
}
};
async function softDelete(data) {
try {
await Patch(dataApi, data["id"], { is_deleted: true })
.then(() => {
toast.success("Record updated successfully!");
getData();
})
.catch((err) => {
getData();
toast.error(err || "Error");
});
} catch {
getData();
toast.error("Something Went wrong contact Humbingo");
}
}
async function restore(data) {
try {
await Patch(dataApi, data["id"], { is_deleted: false })
.then(() => {
toast.success("Record updated successfully!");
getData();
})
.catch((err) => {
getData();
toast.error(err || "Error");
});
} catch {
getData();
toast.error("Something Went wrong contact Humbingo");
}
}
async function forceDelete(data) {
await Swal.fire({
title: "Data will be removed permanently! Are you sure?",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
}).then(async (result) => {
if (result.isConfirmed) {
try {
await Delete(dataApi, data["id"])
.then(() => {
toast.success("Record updated successfully!");
getData();
})
.catch((err) => {
getData();
toast.error(err || "Error");
});
} catch {
getData();
toast.error("Something Went wrong contact Humbingo");
}
}
});
}
const getValueFromUrl = (url, parameterName) => {
try {
const regex = new RegExp(`${parameterName}=([^&]+)`);
const match = url.match(regex);
return match ? match[1] : null;
} catch {
return null;
}
};
function getPageUrl(url) {
let urls = "";
try {
const urlObject = new URL(url);
urls = urlObject.pathname + urlObject.search;
} catch {
return null;
}
return urls;
}
useEffect(() => {
setMounted(true);
return () => {
setMounted(false);
};
}, []);
useEffect(() => {
if (loading && mounted) {
getData();
}
}, [loading, mounted]);
const handleSearchInputChange = (event) => {
const query = event.target.value;
makeApiRequest(dataApi + "?search=" + query);
setSearchQuery(query);
};
const handleSort = (columnKey) => {
const isAsc = orderBy === columnKey && order === "asc";
setOrderBy(columnKey);
setOrder(isAsc ? "desc" : "asc");
setSortedColumn(columnKey);
};
const sortedData = stableSort(filteredData, getComparator(order, orderBy));
const visibleRows = sortedData.slice(
page * rowsPerPage,
page * rowsPerPage + rowsPerPage
);
function stableSort(array, comparator) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
}
function getComparator(order, orderBy) {
return order === "desc"
? (a, b) => descendingComparator(a, b, orderBy)
: (a, b) => -descendingComparator(a, b, orderBy);
}
function descendingComparator(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
const handleMenuClick = (event, rowIndex) => {
setAnchorEls((prev) => ({
...prev,
[rowIndex]: event.currentTarget,
}));
};
const handleMenuClose = (rowIndex) => {
setAnchorEls((prev) => ({
...prev,
[rowIndex]: null,
}));
};
return (
<>
{loading ? (
<center>
<img
src="./assets/img/loader.gif"
height="30px"
width="30px"
alt="Loading"
/>
</center>
) : (
<div className="row">
<Card
className="col-md-12"
style={{ marginBottom: "10px", backgroundColor: "#A9A9A9" }}
>
<CardContent>
{createRequired && (
<FormWithDrawer
globalConfig={props.globalConfig}
token={props.token}
actionBtnName={actionBtnName}
inputFields={createField}
api={dataApi}
createFormTitle={createFormTitle}
refreshData={() => getData()}
buttonStyle={{ margin: "10px", backgroundColor: "#17202A" }}
/>
)}
{searchRequired && (
<div className="search-table">
<input
type="text"
value={searchQuery}
onChange={handleSearchInputChange}
placeholder="Search..."
className="search-input-table"
/>
</div>
)}
</CardContent>
</Card>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow style={{ backgroundColor: "#17202A" }}>
{showField.map((th, index) => {
const isSorted = orderBy === th.key;
const isAsc = orderBy === th.key && order === "asc";
return (
<TableCell
key={index}
style={{ color: "#FFF" }}
onClick={() => handleSort(th.key)}
>
{th.label} {isSorted && (isAsc ? "▲" : "▼")}
</TableCell>
);
})}
{manageRecord && (
<TableCell style={{ textAlign: "center", color: "#FFF" }}>
Action
</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{visibleRows.map((data, rowIndex) => (
<TableRow
key={rowIndex}
style={
data.is_disabled
? {
backgroundColor: "#e0dfff",
borderBottom: "2px dashed orange",
}
: {}
}
>
{showField.map((field, i) => (
<TableCell key={i}>{data[field.key]}</TableCell>
))}
{manageRecord && (
<TableCell>
{editRequired && (
<FormWithDrawer
globalConfig={props.globalConfig}
token={props.token}
actionBtnName="Edit"
inputFields={editField}
data={data}
api={dataApi}
onClick={() => handleMenuClose(rowIndex)}
refreshData={() => getData()}
buttonStyle={{ fontSize: "12px", padding: "5px" }}
buttonVarient="outlined"
updateFormTitle={updateFormTitle}
submitBtnTitle="Update Data"
/>
)}
<Button
id={`fade-button-${rowIndex}`}
aria-controls={
anchorEls[rowIndex]
? `fade-menu-${rowIndex}`
: undefined
}
aria-haspopup="true"
aria-expanded={
anchorEls[rowIndex] ? "true" : undefined
}
onClick={(event) => handleMenuClick(event, rowIndex)}
style={{ padding: "5px" }}
>
<MoreVertIcon />
</Button>
<Menu
id={`fade-menu-${rowIndex}`}
MenuListProps={{
"aria-labelledby": `fade-button-${rowIndex}`,
}}
anchorEl={anchorEls[rowIndex]}
open={Boolean(anchorEls[rowIndex])}
onClose={() => handleMenuClose(rowIndex)}
TransitionComponent={Fade}
>
{data.is_deleted ? (
<MenuItem onClick={() => restore(data)}>
Show Record
</MenuItem>
) : (
<MenuItem onClick={() => softDelete(data)}>
Hide Record
</MenuItem>
)}
<MenuItem onClick={() => forceDelete(data)}>
Remove Record
</MenuItem>
</Menu>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
<Pagination
nextPage={nextPage}
previousPage={previousPage}
makeApiRequest={pageChangeRequest}
getValueFromUrl={getValueFromUrl}
dataApi={dataApi}
totalCount={totalCount}
rowsPerPage={rowsPerPage}
currentPage={currentPage}
setCurrentPage={setCurrentPage}
/>
</TableContainer>
</div>
)}
</>
);
}
export default APIManager;

View File

@ -0,0 +1,109 @@
import React, { useEffect, useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import useApi from "../useApi";
import { toast } from "react-toastify";
const AutoCompleteField = (props) => {
const [api, setApi] = useState(props.api);
const searchOptionHook = props.searchOptionHook;
const fieldLabel = props.label;
const fieldName = props.name;
const optionKey = props.optionKey ? props.optionKey : "id";
const [searchData, setSearchData] = useState([]);
const [storageData, setStorageData] = useState(
JSON.parse(localStorage.getItem("dynamicField"))
);
const [value, setValue] = useState("");
const { Get } = useApi();
const [tempValue, setTempValue] = useState(
storageData
? storageData[storageData.findIndex((item) => item.name === fieldName)]
: ""
);
let newApi = async () => {
let tempApi = api;
if (props.hook != undefined) {
tempApi = `${tempApi}${
storageData[storageData.findIndex((item) => item.name === props.hook)]
.key
}/`;
}
return tempApi;
};
let getdata = async () => {
try{
const tempApi = await newApi();
let response = await Get(tempApi);
let _searchData = [];
await response.data.map((data) => {
_searchData.push({
label: data[searchOptionHook],
key: data[optionKey],
});
});
setSearchData(_searchData);
}catch{
toast.error("Something went wrong contact humbingo.")
}
// await axios
// .get(tempApi)
// .then(async (response) => {
// let _searchData = [];
// await response.data.map((data) => {
// _searchData.push({
// label: data[searchOptionHook],
// key: data[optionKey],
// });
// });
// setSearchData(_searchData);
// })
// .catch((error) => {
// console.error(error);
// });
};
useEffect(() => {
getdata();
}, []);
let getDataFromJson = (e) => {
const acccess = e.target.value;
let respData = searchData.find((f) => f.label === acccess);
respData ? setValue(respData.key) : console.log("this is undefined");
if (props.onBlur != undefined) {
if (respData != undefined) {
props.onBlur(respData);
}
}
};
return searchData.length > 0 ? (
<>
<div style={{ display: "flex" }}>
<div style={{ flex: 1 }}>
<Autocomplete
disablePortal
id="combo-box-demo"
style={props.style}
options={searchData}
onBlur={(e) => getDataFromJson(e)}
value={tempValue}
renderInput={(params) => (
<TextField {...params} label={fieldLabel} variant="standard" />
)}
/>
{/* onSelect={(e) => getDataFromJson(e)} */}
</div>
</div>
<input value={value} name={fieldName} hidden readOnly />
</>
) : (
""
);
};
export default AutoCompleteField;

View File

@ -0,0 +1,416 @@
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Swal from "sweetalert2";
import "./style.css";
import useAPIManager from "./useAPIManager";
import {
Button,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
Menu,
MenuItem,
Fade,
Card,
CardContent,
} from "@mui/material";
import FormWithDrawer from "./FormWithDrawer";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import Pagination from "./Pagination";
function CrudManager(props) {
const dataSchema = props.data;
const { Get, Delete, Patch, getAPI, getHost } = useAPIManager(
props.globalConfig,
props.token
);
const dataApi = getAPI(props.data.api);
const [apiData, setApiData] = useState([]);
const [searchQuery, setSearchQuery] = useState("");
const [orderBy, setOrderBy] = useState(""); // Column to sort
const [order, setOrder] = useState("asc");
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(50);
const [sortedColumn, setSortedColumn] = useState(null);
const [filteredData, setFilteredData] = useState([]);
const [anchorEls, setAnchorEls] = useState({}); // Updated state for menu anchors
const [mounted, setMounted] = useState(false);
const [nextPage, setNextPage] = useState(null);
const [previousPage, setPreviousPage] = useState(null);
const [totalCount, setTotalCount] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [loading, setLoading] = useState(true);
const updateFormTitle = props.updateFormTitle ? props.updateFormTitle : "";
const createFormTitle = props.createFormTitle ? props.createFormTitle : "";
const actionBtnName = props.actionBtnName
? props.actionBtnName
: "Create New Data";
const createRequired = props.createRequired === false ? false : true;
const editRequired = props.editRequired === false ? false : true;
const searchRequired = props.searchRequired === false ? false : true;
const createField = dataSchema.createField;
const editField = dataSchema.editField;
const showField = dataSchema.showField;
const manageRecord = true;
let navigate = useNavigate();
const getData = async () => {
makeApiRequest(dataApi);
};
const makeApiRequest = async (api) => {
try {
setSearchQuery("");
const result = await Get(api ? api : dataApi);
setNextPage(result.next);
setPreviousPage(result.previous);
setTotalCount(result.count);
setApiData(result.results);
setFilteredData(result.results);
} catch (err) {
if (err.code == "ERR_BAD_REQUEST") {
toast.error("Unauthorised access to page, Contact admin for access.");
navigate("/");
} else {
toast.error(err.message);
}
} finally {
setLoading(false);
}
};
const pageChangeRequest = (url) => {
if (getPageUrl(url) != null) {
makeApiRequest(getHost() + getPageUrl(url));
}
};
async function softDelete(data) {
try {
await Patch(dataApi, data["id"], { is_deleted: true })
.then(() => {
toast.success("Record updated successfully!");
getData();
})
.catch((err) => {
getData();
toast.error(err || "Error");
});
} catch {
getData();
toast.error("Something Went wrong contact Humbingo");
}
}
async function restore(data) {
try {
await Patch(dataApi, data["id"], { is_deleted: false })
.then(() => {
toast.success("Record updated successfully!");
getData();
})
.catch((err) => {
getData();
toast.error(err || "Error");
});
} catch {
getData();
toast.error("Something Went wrong contact Humbingo");
}
}
async function forceDelete(data) {
await Swal.fire({
title: "Data will be removed permanently! Are you sure?",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
}).then(async (result) => {
if (result.isConfirmed) {
try {
await Delete(dataApi, data["id"])
.then(() => {
toast.success("Record updated successfully!");
getData();
})
.catch((err) => {
getData();
toast.error(err || "Error");
});
} catch {
getData();
toast.error("Something Went wrong contact Humbingo");
}
}
});
}
const getValueFromUrl = (url, parameterName) => {
try {
const regex = new RegExp(`${parameterName}=([^&]+)`);
const match = url.match(regex);
return match ? match[1] : null;
} catch {
return null;
}
};
function getPageUrl(url) {
let urls = "";
try {
const urlObject = new URL(url);
urls = urlObject.pathname + urlObject.search;
} catch {
return null;
}
return urls;
}
useEffect(() => {
setMounted(true);
return () => {
setMounted(false);
};
}, []);
useEffect(() => {
if (loading && mounted) {
getData();
}
}, [loading, mounted]);
const handleSearchInputChange = (event) => {
const query = event.target.value;
makeApiRequest(dataApi + "?search=" + query);
setSearchQuery(query);
};
const handleSort = (columnKey) => {
const isAsc = orderBy === columnKey && order === "asc";
setOrderBy(columnKey);
setOrder(isAsc ? "desc" : "asc");
setSortedColumn(columnKey);
};
const sortedData = stableSort(filteredData, getComparator(order, orderBy));
const visibleRows = sortedData.slice(
page * rowsPerPage,
page * rowsPerPage + rowsPerPage
);
function stableSort(array, comparator) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
}
function getComparator(order, orderBy) {
return order === "desc"
? (a, b) => descendingComparator(a, b, orderBy)
: (a, b) => -descendingComparator(a, b, orderBy);
}
function descendingComparator(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
const handleMenuClick = (event, rowIndex) => {
setAnchorEls((prev) => ({
...prev,
[rowIndex]: event.currentTarget,
}));
};
const handleMenuClose = (rowIndex) => {
setAnchorEls((prev) => ({
...prev,
[rowIndex]: null,
}));
};
return (
<>
{loading ? (
<center>
<img
src="./assets/img/loader.gif"
height="30px"
width="30px"
alt="Loading"
/>
</center>
) : (
<div className="row">
<Card
className="col-md-12"
style={{ marginBottom: "10px", backgroundColor: "#A9A9A9" }}
>
<CardContent>
{createRequired && (
<FormWithDrawer
globalConfig={props.globalConfig}
token={props.token}
actionBtnName={actionBtnName}
inputFields={createField}
api={dataApi}
createFormTitle={createFormTitle}
refreshData={() => getData()}
buttonStyle={{ margin: "10px", backgroundColor: "#17202A" }}
/>
)}
{searchRequired && (
<div className="search-table">
<input
type="text"
value={searchQuery}
onChange={handleSearchInputChange}
placeholder="Search..."
className="search-input-table"
/>
</div>
)}
</CardContent>
</Card>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow style={{ backgroundColor: "#17202A" }}>
{showField.map((th, index) => {
const isSorted = orderBy === th.key;
const isAsc = orderBy === th.key && order === "asc";
return (
<TableCell
key={index}
style={{ color: "#FFF" }}
onClick={() => handleSort(th.key)}
>
{th.label} {isSorted && (isAsc ? "▲" : "▼")}
</TableCell>
);
})}
{manageRecord && (
<TableCell style={{ textAlign: "center", color: "#FFF" }}>
Action
</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{visibleRows.map((data, rowIndex) => (
<TableRow
key={rowIndex}
style={
data.is_disabled
? {
backgroundColor: "#e0dfff",
borderBottom: "2px dashed orange",
}
: {}
}
>
{showField.map((field, i) => (
<TableCell key={i}>{data[field.key]}</TableCell>
))}
{manageRecord && (
<TableCell>
{editRequired && (
<FormWithDrawer
globalConfig={props.globalConfig}
token={props.token}
actionBtnName="Edit"
inputFields={editField}
data={data}
api={dataApi}
onClick={() => handleMenuClose(rowIndex)}
refreshData={() => getData()}
buttonStyle={{ fontSize: "12px", padding: "5px" }}
buttonVarient="outlined"
updateFormTitle={updateFormTitle}
submitBtnTitle="Update Data"
/>
)}
<Button
id={`fade-button-${rowIndex}`}
aria-controls={
anchorEls[rowIndex]
? `fade-menu-${rowIndex}`
: undefined
}
aria-haspopup="true"
aria-expanded={
anchorEls[rowIndex] ? "true" : undefined
}
onClick={(event) => handleMenuClick(event, rowIndex)}
style={{ padding: "5px" }}
>
<MoreVertIcon />
</Button>
<Menu
id={`fade-menu-${rowIndex}`}
MenuListProps={{
"aria-labelledby": `fade-button-${rowIndex}`,
}}
anchorEl={anchorEls[rowIndex]}
open={Boolean(anchorEls[rowIndex])}
onClose={() => handleMenuClose(rowIndex)}
TransitionComponent={Fade}
>
{data.is_deleted ? (
<MenuItem onClick={() => restore(data)}>
Show Record
</MenuItem>
) : (
<MenuItem onClick={() => softDelete(data)}>
Hide Record
</MenuItem>
)}
<MenuItem onClick={() => forceDelete(data)}>
Remove Record
</MenuItem>
</Menu>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
<Pagination
nextPage={nextPage}
previousPage={previousPage}
makeApiRequest={pageChangeRequest}
getValueFromUrl={getValueFromUrl}
dataApi={dataApi}
totalCount={totalCount}
rowsPerPage={rowsPerPage}
currentPage={currentPage}
setCurrentPage={setCurrentPage}
/>
</TableContainer>
</div>
)}
</>
);
}
export default CrudManager;

View File

@ -0,0 +1,87 @@
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import CircularProgress from '@mui/material/CircularProgress';
import axios from 'axios';
const CustomAutocomplete = ({ apiUrl, displayKey, valueKey, onValueChange, inputName, variant , label, sameAsSeen}) => {
const [options, setOptions] = useState([]);
const [loading, setLoading] = useState(false);
const [inputValue, setInputValue] = useState('');
const [selectedOption, setSelectedOption] = useState(null);
useEffect(() => {
setLoading(true);
axios.get(apiUrl)
.then(response => {
setOptions(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
})
.finally(() => {
setLoading(false);
});
}, [apiUrl]);
const handleInputChange = (event, newValue) => {
setInputValue(newValue);
};
const handleOptionSelect = (event, newValue) => {
// console.log("Selected value:");
// console.log(newValue);
setSelectedOption(newValue);
setInputValue(newValue ? newValue[displayKey] : '');
onValueChange(newValue, inputName); // Pass the name attribute value along with the value
};
return (
<>
<Autocomplete
inputValue={inputValue}
onInputChange={handleInputChange}
options={options}
loading={loading}
onChange={handleOptionSelect}
getOptionLabel={(option) => option ? option[displayKey] : ''}
renderInput={(params) => (
<TextField
{...params}
label={label}
variant={variant}
InputProps={{
...params.InputProps,
endAdornment: (
<>
{loading ? <CircularProgress color="secondary" size={20} /> : null}
{params.InputProps.endAdornment}
</>
),
}}
/>
)}
/>
<input hidden name={inputName} value={selectedOption ? selectedOption[valueKey] : ''} style={{display: 'none'}}/>
{(sameAsSeen)?<input hidden name={"_"+inputName} value={selectedOption ? selectedOption[displayKey] : ''} style={{display: 'none'}}/>:""}
</>
);
};
CustomAutocomplete.propTypes = {
apiUrl: PropTypes.string.isRequired,
displayKey: PropTypes.string.isRequired,
valueKey: PropTypes.string.isRequired,
onValueChange: PropTypes.func.isRequired,
inputName: PropTypes.string.isRequired, // Accept inputName prop
};
export default CustomAutocomplete;

View File

@ -0,0 +1,112 @@
import React, { useState } from 'react';
import CustomAutocomplete from './Autocomplete';
import _Autocomplete from './_Autocomplete';
const DynamicAutocomplete = (props) => {
// [
// {
// "apiUrl": 'https://api.udaymotors.in/api/v1/user/',
// "displayKey": 'phone_no',
// "valueKey": 'id',
// "name": "user",
// "label":"User"
// },
// {
// "apiUrl": 'https://api.udaymotors.in/api/v1/getInvestmentsByUserId/',
// "displayKey": 'investment_id',
// "valueKey": 'id',
// "name": "investment",
// "parent": "user",
// "parent_value_key": "id",
// "label":"Investments"
// },
// {
// "apiUrl": 'https://api.udaymotors.in/api/v1/transaction/',
// "displayKey": 'description',
// "name": "transaction",
// "valueKey": 'id',
// "parent": "investment",
// "parent_value_key": "user_id",
// "label":"Transactions"
// },
// ]
const [selectedValues, setSelectedValues] = useState([]);
const [currentFieldIndex, setCurrentFieldIndex] = useState(0);
const [fields, setFields] = useState(props.fields);
const handleValueChange = (value, name) => {
const updatedValues = [...selectedValues];
const existingIndex = updatedValues.findIndex(item => item.name === name);
if (existingIndex !== -1) {
updatedValues[existingIndex] = { value, name };
} else {
updatedValues.push({ value, name });
}
setSelectedValues(updatedValues);
// Update the API URL of the next field
const nextFieldIndex = currentFieldIndex + 1;
if (nextFieldIndex < fields.length) {
const nextField = fields[nextFieldIndex];
const parentValue = updatedValues.find(item => item.name === nextField.parent)?.value[nextField.parent_value_key];
if (parentValue) {
const updatedFields = [...fields];
updatedFields[nextFieldIndex] = {
...nextField,
apiUrl: `${nextField.apiUrl}${parentValue}/`
};
setFields(updatedFields);
}
}
setCurrentFieldIndex(nextFieldIndex);
};
const handleParentValueChange = (parentName, parentValue) => {
// Find the index of the parent field
const parentFieldIndex = fields.findIndex(field => field.name === parentName);
// Reset the selected values and fields configurations for the subsequent fields
setSelectedValues(selectedValues.slice(0, parentFieldIndex + 1));
setFields(fields.slice(0, parentFieldIndex + 1));
setCurrentFieldIndex(parentFieldIndex);
};
return (
fields.slice(0, currentFieldIndex + 1).map((field, index) => (
<div key={index} style={{marginTop: "10px", marginBottom: "10px"}}>
{
(field.advance)?
<_Autocomplete
apiUrl={field.apiUrl}
displayKey={field.displayKey}
valueKey={field.valueKey}
inputName={field.name}
onValueChange={handleValueChange}
onParentValueChange={handleParentValueChange}
variant={field.variant}
label={field.label}
sameAsSeen={field.sameAsSeen}
defaultObj={(field.defaultObj)?field.defaultObj:""}
/>
:<CustomAutocomplete
apiUrl={field.apiUrl}
displayKey={field.displayKey}
valueKey={field.valueKey}
inputName={field.name}
onValueChange={handleValueChange}
onParentValueChange={handleParentValueChange}
variant={field.variant}
label={field.label}
sameAsSeen={field.sameAsSeen}
/>
}
</div>
))
);
}
export default DynamicAutocomplete;

View File

@ -0,0 +1,109 @@
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import CircularProgress from '@mui/material/CircularProgress';
import useAPIManager from '../useAPIManager';
const _Autocomplete = (props) => {
const {
apiUrl,
displayKey,
valueKey,
onValueChange,
inputName,
variant,
label,
sameAsSeen,
defaultObj,
onBlur,
onFocus,
options: propOptions
} = props;
const [options, setOptions] = useState(propOptions || []);
const [loading, setLoading] = useState(false);
const [inputValue, setInputValue] = useState('');
const [selectedOption, setSelectedOption] = useState(defaultObj);
const {Get, Post} =useAPIManager(props.globalConfig, props.token);
useEffect(() => {
setLoading(true);
getSearchData(apiUrl)
}, [apiUrl]);
const handleInputChange = (event, newValue) => {
getSearchData(apiUrl+"?search="+newValue)
setInputValue(newValue);
};
const getSearchData = async (api) =>{
await Get(api)
.then(response => {
(response.results)?setOptions(response.results):setOptions(response)
})
.catch(error => {
console.error('Error fetching data:', error);
})
.finally(() => {
setLoading(false);
});
}
const handleOptionSelect = (event, newValue) => {
setSelectedOption(newValue);
setInputValue(newValue ? newValue[displayKey] : '');
onValueChange(newValue, inputName); // Pass the name attribute value along with the value
};
return (
<>
<Autocomplete
inputValue={inputValue}
onInputChange={handleInputChange}
options={options}
loading={loading}
onChange={handleOptionSelect}
getOptionLabel={(option) => option ? option[displayKey] : ''}
defaultValue= { defaultObj}
renderInput={(params) => (
<TextField
{...params}
label={label}
variant={variant}
onBlur={onBlur}
onFocus={onFocus}
InputProps={{
...params.InputProps,
endAdornment: (
<>
{loading ? <CircularProgress color="secondary" size={20} /> : null}
{params.InputProps.endAdornment}
</>
),
}}
/>
)}
/>
{/* {console.log(selectedOption)} */}
<input hidden name={inputName} value={selectedOption ? selectedOption[valueKey] : ''} style={{display: 'none'}}/>
{(sameAsSeen)?<input hidden name={"_"+inputName} value={selectedOption ? selectedOption[displayKey] : ''} style={{display: 'none'}}/>:""}
</>
);
};
_Autocomplete.propTypes = {
apiUrl: PropTypes.string.isRequired,
displayKey: PropTypes.string.isRequired,
valueKey: PropTypes.string.isRequired,
onValueChange: PropTypes.func.isRequired,
inputName: PropTypes.string.isRequired, // Accept inputName prop
};
export default _Autocomplete;

View File

@ -0,0 +1,84 @@
import React, { useState } from "react";
import Drawer from "@mui/material/Drawer";
import { Button, TextField } from "@mui/material";
import { firstUpperCase } from "./helper.js";
function EditRow(props) {
const editBlock = props.editBlock ? props.editBlock : [];
const [state, setState] = React.useState({
top: false,
left: false,
bottom: false,
right: false,
});
const toggleDrawer = (anchor, open) => (event) => {
if (
event.type === "keydown" &&
(event.key === "Tab" || event.key === "Shift")
) {
return;
}
setState({ ...state, [anchor]: open });
};
const [formFields, setFormFields] = useState(props.data);
var fields = Object.keys(formFields);
const handleSubmit = (e) => {
e.preventDefault();
};
function doChange(fieldName, value) {
setFormFields((prevData) => ({
...prevData,
[fieldName]: value,
}));
localStorage.setItem(props.data.id + "_" + fieldName, value);
}
return (
<>
{/* {formFields} */}
{["right"].map((anchor) => (
<React.Fragment key={anchor}>
<Button onClick={toggleDrawer(anchor, true)}>Edit</Button>
<Drawer
anchor={anchor}
open={state[anchor]}
onClose={toggleDrawer(anchor, false)}
>
<div className="row" style={{ padding: "10px", width: "500px" }}>
<div className="col-md-12">
<h4>Edit Details</h4>
<form onSubmit={handleSubmit}>
{fields.map((field, index) => {
return (
<div key={index} className="dynamic-form-element">
{!Object.values(editBlock).includes(field) ? (
<>
{" "}
<TextField
variant="standard"
name={field}
value=""
onChange={(e) => doChange(field, e.target.value)}
label={firstUpperCase(field)}
/>
<br />{" "}
</>
) : (
""
)}
</div>
);
})}
<Button variant="outlined" type="submit">
Update
</Button>
</form>
</div>
</div>
</Drawer>
</React.Fragment>
))}
</>
);
}
export default EditRow;

View File

@ -0,0 +1,17 @@
import React from 'react'
import CrudManager from './CrudManager'
import schema from './example.json'
const CrudManagerExample = () => {
return (
<>
<CrudManager data={schema} />
{/* // <CRUDManager schema={schema}/> */}
</>
)
}
export default CrudManagerExample

148
src/api-manager/Form.js Normal file
View File

@ -0,0 +1,148 @@
import React,{useState} from "react";
import { Button } from "@mui/material";
import FormField, { validateField } from "./FormField";
import "./style.css";
import { toast } from "react-toastify";
import useAPIManager from "./useAPIManager";
const Form = (props) => {
const inputFields = props.inputFields;
const fieldDefault = props.data ? props.data : [];
const submitBtnTitle = props.submitBtnTitle ? props.submitBtnTitle : "Submit";
const [externalErrors, setExternalErrors] = useState({});
const { Get, Delete, Patch, Post, getHost } = useAPIManager(
props.globalConfig,
props.token
);
async function handleSubmit(e) {
e.preventDefault();
let isFormValid = true;
const newExternalErrors = {};
inputFields.forEach((field) => {
const fieldName = field.name;
const value = e.target.elements[fieldName].value;
const validationError = validateField(value, field.type, field.label);
if (field.required) { // Check if the field is required
const validationError = validateField(value, field.type, field.label);
if (validationError) {
newExternalErrors[fieldName] = validationError;
toast.error(validationError);
isFormValid = false;
}
}
});
setExternalErrors(newExternalErrors);
if (!isFormValid) {
return; // Don't submit if form is invalid
}
var data = new FormData(e.target);
let formData = Object.fromEntries(data.entries());
// console.log(formData);
if (fieldDefault["id"]) {
try{
await Patch(props.api,fieldDefault["id"], formData).then(()=>{
props.closeDrawer();
props.refreshData();
toast.success("Record updated successfully!");
})
.catch((err) => {
// console.error(err);
toast.error(err || "Error");
});
}catch{
toast.error("Something Went wrong contact Humbingo");
}
// axios
// .patch(props.api + `${fieldDefault["id"]}` + "/", formData)
// .then((response) => {
// props.closeDrawer();
// props.refreshData();
// toast.success("Record updated successfully!");
// })
// .catch((err) => {
// // console.error(err);
// toast.error(err.response?.data?.error || "An error occurred");
// });
} else {
try{
await Post(props.api, formData).then(()=>{
props.closeDrawer();
props.refreshData();
toast.success("Record created successfully!");
})
.catch((err) => {
// console.error(err);
toast.error(err.response?.data?.error || "Error");
});
}catch{
toast.error("Something Went wrong contact Humbingo");
}
// axios
// .post(props.api, formData)
// .then((response) => {
// props.closeDrawer();
// props.refreshData();
// toast.success("Record created successfully!");
// })
// .catch((err) => {
// // console.error(err);
// toast.error(err.response?.data?.error || "An error occurred");
// });
}
}
return (
<form onSubmit={handleSubmit} style={{ padding: "20px" }}>
{inputFields.map((field, index) => {
const fieldName = field["name"];
if (props.grid) {
return (
<div className={props.grid}>
<div className="dynamic-form-element" key={index}>
<FormField
globalConfig={props.globalConfig}
token={props.token}
field={field}
name={index}
defaultValue={fieldDefault[fieldName]}
handleChange={props.handleChange}
/>
</div>
</div>
);
} else {
return (
<div className="dynamic-form-element" key={index}>
<FormField
globalConfig={props.globalConfig}
token={props.token}
field={field}
name={index}
defaultValue={fieldDefault[fieldName]}
handleChange={props.handleChange}
/>
</div>
);
}
})}
<br />
<Button variant="contained" type="submit" size="small">
{submitBtnTitle}
</Button>
</form>
);
};
export default Form;

View File

@ -0,0 +1,314 @@
import React, { useEffect, useState } from "react";
import { TextField, FormHelperText } from "@mui/material";
import { firstUpperCase ,validateEmail,validatePassword} from "./helper.js";
import "./style.css";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/material/Checkbox";
import CustomAutocomplete from "./DynamicForm/Autocomplete.js";
import _Autocomplete from "./DynamicForm/_Autocomplete.js";
import useAPIManager from './useAPIManager.js';
export const validateField = (value, type, label) => {
let errorMessage = "";
if (label) {
switch (type) {
case "text":
if (!value) {
errorMessage = ` ${label} is required`;
}
break;
case "select":
if (!value) {
errorMessage = ` ${label} Please Select Value`;
}
break;
case "simple-select":
if (!value) {
errorMessage = ` ${label} Please Select`;
}
break;
case "advance-select":
if (!value) {
errorMessage = ` ${label} Please Select`;
}
break;
case "datetime-local":
if (!value) {
errorMessage = `${label} Please Select `;
}
break;
case "checkbox":
if (!value) {
errorMessage = `${label} Must be Checked`;
}
break;
case "email":
if (!value || !validateEmail(value)) {
errorMessage = `${label} must be a valid email address`;
}
break;
case "password":
if (!value || !validatePassword(value)) {
errorMessage = `${label} must be at least 8 characters long`;
}
break;
case "phone":
if (!value || value.length !== 10) {
errorMessage = `${label} must be exactly 10 characters`;
}
break;
default:
if (!value || !value.trim()) {
errorMessage = `${label} Is Required`;
}
}
}
return errorMessage;
};
const FormField = (props) => {
const { Get, Delete, Patch, Post, getAPI } = useAPIManager(
props.globalConfig,
props.token
);
const required = props.field.required;
const label = firstUpperCase(props.field.label);
let fieldLabel = required ? (
<span>
<b style={{ color: "red" }}>*</b> {label}
</span>
) : (
label
);
const type = props.field.type;
const varient = props.field.varient;
const placeholder = props.field.placeholder;
const isDynamic = props.field.dynamic;
const hook = props.field.hook;
const defaultObj = props.field.defaultObj;
const dafaultValue = props.field.defaultValue
? props.field.defaultValue
: props.defaultValue;
const name = props.field.name;
let optionKey = "";
let searchApi = "";
let searchOptionHook = "";
if (props.field.search) {
searchApi = props.field.search.api ? props.field.search.api : "";
// console.log("My Search APu 1", searchApi);
searchApi = searchApi.length > 0 ? getAPI(searchApi) : "";
searchOptionHook = props.field.search.label ? props.field.search.label : "";
optionKey = props.field.search.key ? props.field.search.key : "id";
}
const [value, setValue] = useState(dafaultValue);
const [isChecked, setIsChecked] = useState(dafaultValue);
const [storageData, setStorageData] = useState([]);
const [error, setError] = useState(
props.field.error ? props.field.error : ""
);
const [blurred, setBlurred] = useState(false);
const [simpleSelectOptions, setSimpleSelectOptions] = useState(
props.field.options
);
useEffect(() => {
const storedData = localStorage.getItem("dynamicField");
if (storedData) {
setStorageData(JSON.parse(storedData));
}
}, []);
const updateKey = (name, newKey, newLabel) => {
const newData = [...storageData];
const dataIndex = newData.findIndex((item) => item.name === name);
if (dataIndex !== -1) {
newData[dataIndex].key = newKey;
newData[dataIndex].label = newLabel;
} else {
newData.push({ name, key: newKey, label: newLabel });
}
setStorageData(newData);
// Update local storage with the new data
localStorage.setItem("dynamicField", JSON.stringify(newData));
};
const changeField = async (e) => {
if (e != undefined && e != null) {
updateKey(name, e.key, e.label);
window.location.reload();
}
};
let handleOnChange = (e) => {
setValue(e.target.value);
if (blurred) {
setError(validateField(e.target.value, type, label));
}
};
const handleChange = () => {
const newChecked = !isChecked;
setIsChecked(newChecked);
if (blurred) {
setError(validateField(newChecked, type, label));
}
};
const handleaAutocompleteChange = (newValue, inputName) => {
setValue(newValue);
if (blurred) {
setError(validateField(newValue.target.value, type, label));
}
};
const handleBlur = (e) => {
setBlurred(true);
setError(validateField(value, type, label));
setError(
validateField(type === "checkbox" ? isChecked : value, type, label)
);
// Validate the field when blurred
};
const handleFocus = () => {
setBlurred(false);
};
const renderError = () => {
// Check if validation is required for this field
const isValidationRequired = required || false;
if (isValidationRequired && error && blurred) {
return <FormHelperText error>{error}</FormHelperText>;
}
return null;
};
function formatDate(inputDate) {
const date = new Date(inputDate);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
switch (type) {
case "select":
return (
<>
<CustomAutocomplete
apiUrl={searchApi}
displayKey={searchOptionHook}
valueKey={optionKey}
inputName={name}
onValueChange={() => {}}
variant={varient}
label={fieldLabel}
onBlur={handleBlur}
onFocus={handleFocus}
/>
{renderError()}
</>
);
case "simple-select":
return (
<>
<_Autocomplete
globalConfig={props.globalConfig}
token={props.token}
apiUrl=""
displayKey="label"
valueKey="type"
inputName={name}
onValueChange={handleaAutocompleteChange}
variant={varient}
label={label}
defaultObj={defaultObj}
options={simpleSelectOptions}
onBlur={handleBlur}
onFocus={handleFocus}
/>
{renderError()}
</>
);
case "advance-select":
return (
<div style={{ position: "relative" }}>
<_Autocomplete
globalConfig={props.globalConfig}
token={props.token}
apiUrl={searchApi}
displayKey={searchOptionHook}
valueKey={optionKey}
inputName={name}
onValueChange={handleaAutocompleteChange}
variant={varient}
label={fieldLabel}
onBlur={handleBlur}
onFocus={handleFocus}
defaultObj={defaultObj}
/>
{renderError()}
</div>
);
case "checkbox":
return (
<div onBlur={handleBlur} onFocus={handleFocus}>
<FormControlLabel
control={<Checkbox checked={isChecked} onChange={handleChange} />}
label={fieldLabel}
name={name}
/>
{renderError()}
</div>
);
case "datetime-local":
return (
<div style={{ textAlign: "left" }}>
<TextField
name={name}
label={fieldLabel}
type={type}
style={{ width: "100%" }}
variant={varient}
placeholder={placeholder}
value={formatDate(value)}
onChange={handleOnChange}
onBlur={handleBlur}
onFocus={handleFocus}
/>
{renderError()}
</div>
);
default:
return (
<div style={{ position: "relative" }}>
<TextField
name={name}
label={fieldLabel}
type={type}
style={{ width: "100%" }}
variant={varient}
placeholder={placeholder}
value={value}
onChange={handleOnChange}
onBlur={handleBlur}
onFocus={handleFocus}
/>
{renderError()}
</div>
);
}
};
export default FormField;

View File

@ -0,0 +1,77 @@
import React from "react";
import { Button } from "@mui/material";
import Drawer from "@mui/material/Drawer";
import Form from "./Form";
const FormWithDrawer = (props) => {
const [state, setState] = React.useState({
top: false,
left: false,
bottom: false,
right: false,
});
const toggleDrawer = (anchor, open) => (event) => {
if (
event.type === "keydown" &&
(event.key === "Tab" || event.key === "Shift")
) {
return;
}
setState({ ...state, [anchor]: open });
};
const anchor = props.anchor ? props.anchor : "right";
const actionBtnName = props.actionBtnName;
const data = props.data;
const buttonVarient = props.buttonVarient ? props.buttonVarient : "contained";
const updateFormTitle = props.updateFormTitle ? props.updateFormTitle : "";
const createFormTitle = props.createFormTitle ? props.createFormTitle : "";
const submitBtnTitle = props.submitBtnTitle ? props.submitBtnTitle : "Submit";
const handleCloseDrawer = () => {
setState({ ...state, [anchor]: false });
};
return (
<React.Fragment key={anchor}>
<Button
onClick={toggleDrawer(anchor, true)}
variant={buttonVarient}
style={props.buttonStyle}
>
{actionBtnName}
</Button>
<Drawer
anchor={anchor}
open={state[anchor]}
onClose={toggleDrawer(anchor, false)}
>
<div className="row" style={{ width: "470px" }}>
<div
className="col-md-12"
style={{ textAlign: "center", color: "#333", padding: "10px" }}
>
<h4>{createFormTitle}</h4>
<h4>{updateFormTitle}</h4>
<hr />
<div>
<Form
globalConfig={props.globalConfig}
token={props.token}
closeDrawer={handleCloseDrawer}
refreshData={() => props.refreshData()}
submitBtnTitle={submitBtnTitle}
inputFields={props.inputFields}
api={props.api}
data={data}
/>
</div>
</div>
</div>
</Drawer>
</React.Fragment>
);
};
export default FormWithDrawer;

View File

@ -0,0 +1,57 @@
import React, { useEffect, useState } from "react";
import AutoCompleteField from "./AutoCompleteField";
import FormField from "./FormField";
const MultiSelect = (props) => {
const [hookObj, setHookObj] = useState([]);
let handleOnChange = (key, value) => {
let obj = [];
console.log("Field Changed sfsdfds", key, value);
localStorage.setItem(key, value);
// setHookObj(hookObj => [...hookObj,{"name":key, "value":value}]);
console.log("Multi Dtaa", hookObj);
};
let loadWithUpdatedApi = (field)=>{
// field.search.api=localStorage.getItem(field.search.hook) ;
console.log("Sub Search Hook",field.search.hook);
field.search.api = `http://127.0.0.1:8000/api/v1/getAllGroupsJoinedByUser/${localStorage.getItem(field.search.hook)}/`;
return(<FormField
FormField
handleChange={(name, value) => handleOnChange(name, value)}
field={field}
/>)
}
useEffect(()=>{
},[])
let updateRefresh = (refresh)=>{
console.log(refresh);
}
return (
<div>
<code>{JSON.stringify(props.field)}</code>
{props.field.map((f) => {
return f.search.hook ? (
loadWithUpdatedApi(f)
) : (
<FormField
FormField
handleChange={(name, value) => handleOnChange(name, value)}
refresh={(refresh) => updateRefresh(refresh)}
field={f}
/>
);
})}
</div>
);
};
export default MultiSelect;

View File

@ -0,0 +1,98 @@
import React from "react";
import { Button } from "@mui/material";
import "./style.css";
function Pagination({
nextPage,
previousPage,
makeApiRequest,
getValueFromUrl,
totalCount,
rowsPerPage,
currentPage,
setCurrentPage,
dataApi,
}) {
const totalPages = Math.ceil(totalCount / rowsPerPage);
const generatePageNumbers = () => {
const pages = [];
const maxPages = 4;
const currentPageIndex = currentPage;
let startPage = Math.max(1, currentPageIndex - Math.floor(maxPages / 2));
let endPage = Math.min(totalPages, startPage + maxPages - 1);
if (endPage === totalPages) {
startPage = Math.max(1, endPage - maxPages + 1);
} else if (startPage === 1) {
endPage = Math.min(totalPages, startPage + maxPages - 1);
}
for (let i = startPage; i <= endPage; i++) {
pages.push(i);
}
return pages;
};
const handlePreviousClick = () => {
if (previousPage) {
const previousPageNumber = currentPage - 1;
setCurrentPage(previousPageNumber);
makeApiRequest(previousPage);
}
};
const handleNextClick = () => {
if (nextPage) {
const nextPageNumber = currentPage + 1;
setCurrentPage(nextPageNumber);
makeApiRequest(nextPage);
}
};
return (
<div className="pagination-container">
<Button
disabled={!previousPage}
onClick={handlePreviousClick}
variant="outlined"
className="pagination-button"
style={{ margin: "5px" }}
>
Previous
</Button>
{generatePageNumbers().map((page) => (
<Button
key={page}
onClick={() => {
setCurrentPage(page);
const apiPage = nextPage
? `${nextPage.split("page=")[0]}page=${page}`
: `${dataApi}?page=${page}`;
makeApiRequest(apiPage);
}}
variant="outlined"
className={`pagination-button ${
currentPage === page ? "active-page" : ""
}`}
style={{ margin: "5px" }}
>
{page}
</Button>
))}
<Button
disabled={!nextPage}
onClick={handleNextClick}
variant="outlined"
className="pagination-button"
style={{ margin: "5px" }}
>
Next
</Button>
</div>
);
}
export default Pagination;

View File

@ -0,0 +1,33 @@
import * as React from "react";
import Radio from "@mui/material/Radio";
import RadioGroup from "@mui/material/RadioGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormControl from "@mui/material/FormControl";
import FormLabel from "@mui/material/FormLabel";
export default function RadioButtonsGroup() {
return (
<FormControl>
<FormLabel id="demo-radio-buttons-group-label">Payment In For </FormLabel>
<RadioGroup
aria-labelledby="demo-radio-buttons-group-label"
defaultValue="subscription_amt"
name="transaction_type"
row
>
<FormControlLabel
value="subscription_amt"
control={<Radio />}
label="Subscription"
/>
{/* <FormControlLabel value="penalty" control={<Radio />} label="Penalty" /> */}
<FormControlLabel
value="draw_winner"
control={<Radio />}
label="Draw Winner"
/>
{/* <FormControlLabel value="custom_amt" control={<Radio />} label="Custom Amount" /> */}
</RadioGroup>
</FormControl>
);
}

View File

@ -0,0 +1,52 @@
import { Button } from '@mui/material';
import React from 'react'
import EditRow from './EditRow';
import FormWithDrawer from './FormWithDrawer';
function TableRow(props) {
var row = [];
const readBlock = (props.readBlock) ? props.readBlock : [];
function getCellArray() {
Object.keys(props.data).forEach((key) => {
console.log(readBlock);
if (!Object.values(readBlock).includes(key)) {
Object.entries(props.data).forEach((entry) => {
if (key === entry[0]) {
row.push(entry[1]);
}
})
}
})
}
function removeRow() { }
getCellArray();
return (
<tr>
{
row.map((data, index) => {
return <td key={index}>{data}</td>
})
}
{(props.manage) ? <>
<td>
<Button onClick={() => removeRow()}> Delete</Button>
</td>
<td>
<FormWithDrawer actionBtnName="Edit Data" inputFields={{}} api="https://api.udaymotors.in/api/v1/role/" />
{/* <EditRow data={props.data} /> */}
</td>
</> : ""
}
</tr>
)
}
export default TableRow

View File

@ -0,0 +1,105 @@
{
"api":"https://api.udaymotors.in/api/v1/group/"
,
"showField":[
{ "label": "Group Name", "key": "title" },
{ "label": "Description", "key": "description" },
{ "label": "Subscription Amount", "key": "subscription_amt" },
{ "label": "Max Allowed Users", "key": "max_users" },
{ "label": "Penalty Amount", "key": "penalty_amt" },
{ "label": "Start Date", "key": "start_date" },
{ "label": "End Date", "key": "end_date" }
],
"createField":[
{
"label": "Group name",
"type": "text",
"variant": "standard",
"name": "title"
},
{
"label": "Group Description",
"type": "text",
"variant": "standard",
"name": "description"
},
{
"label": "Start Date",
"type": "datetime-local",
"variant": "standard",
"name": "start_date"
},
{
"label": "End Date",
"type": "datetime-local",
"variant": "standard",
"name": "end_date"
},
{
"label": "Max Users",
"type": "text",
"variant": "standard",
"name": "max_users"
},
{
"label": "Subscription Amount",
"type": "text",
"variant": "standard",
"name": "subscription_amt"
},
{
"label": "Panelty Amount",
"type": "text",
"variant": "standard",
"name": "penalty_amt"
}
],
"editField":[
{
"label": "Group name",
"type": "text",
"variant": "standard",
"name": "title"
},
{
"label": "Group Description",
"type": "text",
"variant": "standard",
"name": "description"
},
{
"label": "Start Date",
"type": "datetime-local",
"variant": "standard",
"name": "start_date"
},
{
"label": "End Date",
"type": "datetime-local",
"variant": "standard",
"name": "end_date"
},
{
"label": "Max Users",
"type": "text",
"variant": "standard",
"name": "max_users"
},
{
"label": "Subscription Amount",
"type": "text",
"variant": "standard",
"name": "subscription_amt"
},
{
"label": "Panelty Amount",
"type": "text",
"variant": "standard",
"name": "penalty_amt"
}
]
}

16
src/api-manager/helper.js Normal file
View File

@ -0,0 +1,16 @@
export function camelCase(str) {
// Using replace method with regEx
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
export function firstUpperCase(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export const validateEmail = (email) => {
const emailRegex = /^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
};
export const validatePassword = (password) => {
return password.length >= 8;
};

46
src/api-manager/style.css Normal file
View File

@ -0,0 +1,46 @@
.dynamic-form-element {
display: block;
margin-bottom: 10px;
width: 100%;
}
.search-table {
display: flex;
align-items: center;
padding-top: 15px;
padding-bottom: 15px;
width: 100%;
}
.search-input-table {
padding: 8px;
border: none; /* Remove border */
border-radius: 15px;
outline: none;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
font-size: 16px;
width: 100%;
height: 30px;
}
.search-input-table:focus {
background-color: #f0f0f0; /* Optional: Change background color on focus */
}
/* pagination */
.pagination-container {
display: flex;
justify-content: center;
align-items: center;
margin: 20px 0;
}
.pagination-button {
margin: 0 5px;
}
.pagination-button.active-page {
background-color: #6c757d;
color: rgb(73, 198, 207);
}

View File

@ -0,0 +1,77 @@
import axios from "axios";
const useAPIManager = (globalConfig, _token) => {
const authToken = _token;
const global = globalConfig;
let token = authToken.access;
let authorization = _token
? {
headers: {
Authorization: `Bearer ${token}`,
},
}
: {};
const getAPI = (API_NAME) => global.api.host + global.api[API_NAME];
const getHost = () => global.api.host;
const Post = async (api, payload) => {
let _api = getAPI(api).includes("undefined") ? api : getAPI(api);
try {
const response = await axios.post(_api, payload, authorization);
return response;
} catch (err) {
throw err;
}
};
const Put = async (api, id, payload) => {
let _api = getAPI(api).includes("undefined") ? api : getAPI(api);
try {
const response = await axios.put(`${_api}${id}/`, payload, authorization);
return response;
} catch (err) {
throw err;
}
};
const Patch = async (api, id, payload) => {
let _api = getAPI(api).includes("undefined") ? api : getAPI(api);
try {
const response = await axios.patch(
`${_api}${id}/`,
payload,
authorization
);
return response;
} catch (err) {
throw err;
}
};
const Get = async (api) => {
let _api = getAPI(api).includes("undefined") ? api : getAPI(api);
try {
const response = await axios.get(_api, authorization);
return response.data;
} catch (err) {
throw err;
}
};
const Delete = async (api, id) => {
let _api = getAPI(api).includes("undefined") ? api : getAPI(api);
try {
const response = await axios.delete(`${_api}${id}/`, authorization);
return response;
} catch (err) {
throw err;
}
};
return { Post, Put, Patch, Get, Delete, getAPI, getHost };
};
export default useAPIManager;

89
src/api-manager/useApi.js Normal file
View File

@ -0,0 +1,89 @@
// useApi.js
import { useContext } from 'react';
import axios from 'axios';
import AuthContext from '../auth/AuthContext';
import global from '../global/GlobalJSON.json';
const useApi = () => {
const { authToken } = useContext(AuthContext);
const getAPI = (API_NAME) => global.api.host + global.api[API_NAME];
const getHost = () => global.api.host;
let token = authToken.access;
const Post = async (api, payload) => {
let _api =(getAPI(api).includes('undefined'))?api:getAPI(api);
try {
const response = await axios.post(_api, payload, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response;
} catch (err) {
throw err;
}
};
const Put = async (api, id, payload) => {
let _api =(getAPI(api).includes('undefined'))?api:getAPI(api);
try {
const response = await axios.put(`${_api}${id}/`, payload, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response;
} catch (err) {
throw err;
}
};
const Patch = async (api, id, payload) => {
let _api =(getAPI(api).includes('undefined'))?api:getAPI(api);
try {
const response = await axios.patch(`${_api}${id}/`, payload, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response;
} catch (err) {
throw err;
}
};
const Get = async (api) => {
let _api =(getAPI(api).includes('undefined'))?api:getAPI(api);
try {
const response = await axios.get(_api, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.data;
} catch (err) {
throw err;
}
};
const Delete = async (api, id) => {
let _api =(getAPI(api).includes('undefined'))?api:getAPI(api);
try {
const response = await axios.delete(`${_api}${id}/`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response;
} catch (err) {
throw err;
}
};
return { Post, Put, Patch, Get, Delete, getAPI, getHost };
};
export default useApi;

BIN
src/assets/bg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

131
src/auth/AuthContext.js Normal file
View File

@ -0,0 +1,131 @@
import { createContext, useEffect, useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import {jwtDecode} from "jwt-decode"; // Make sure jwt-decode is imported correctly
import { getAPI } from "../global/Global"; // Make sure this function is properly defined
import { toast } from "react-toastify";
const AuthContext = createContext();
export default AuthContext;
export const AuthProvider = ({ children }) => {
const [authToken, setAuthToken] = useState(() =>
localStorage.getItem("authToken") ? JSON.parse(localStorage.getItem("authToken")) : null
);
const [user, setUser] = useState(() =>
localStorage.getItem("authToken") ? jwtDecode(localStorage.getItem("authToken")) : {}
);
const navigate = useNavigate();
const [loading, setLoading] = useState(true);
const loginUser = (e) => {
e.preventDefault();
axios
.post(getAPI("token"), {
username: e.target.username.value,
password: e.target.password.value,
})
.then((response) => {
checkSuperUser(response.data.access);
setAuthToken(response.data);
setUser(jwtDecode(response.data.access));
localStorage.setItem("authToken", JSON.stringify(response.data));
})
.catch((error) => {
toast.error("Username or password incorrect");
console.error(error);
});
};
const checkSuperUser = async (token) => {
try {
const response = await axios.get(getAPI("isSuperUser"), {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.data.is_superuser) {
toast.success("Welcome, Admin");
} else {
logOutUser("User is not super user");
}
} catch (error) {
toast.error("Error checking user permissions");
console.error(error);
}
};
const refreshToken = () => {
if (authToken?.refresh) {
axios
.post(getAPI("refreshToken"), { refresh: `${authToken.refresh}` })
.then((response) => {
checkSuperUserRefresh(response.data.access);
setAuthToken(response.data);
setUser(jwtDecode(response.data.access));
localStorage.setItem("authToken", JSON.stringify(response.data));
})
.catch(logOutUser); // Log out if there's an error
} else {
logOutUser();
}
if (loading) {
setLoading(false);
}
};
const logOutUser = (message) => {
setAuthToken(null);
setUser({});
localStorage.removeItem("authToken");
if (message) toast.error(message);
navigate("login");
};
const checkSuperUserRefresh = async (token) => {
try {
const response = await axios.get(getAPI("isSuperUser"), {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.data.is_superuser) {
logOutUser("User is not super user");
}
} catch (error) {
toast.error("Error checking user permissions");
console.error(error);
}
};
useEffect(() => {
if (loading) {
refreshToken();
}
const fourMinutes = 1000 * 60 * 4;
const interval = setInterval(() => {
if (authToken) {
refreshToken();
}
}, fourMinutes);
return () => clearInterval(interval);
}, [authToken, loading]);
const contextData = {
user,
loginUser,
logOutUser,
authToken,
};
return (
<AuthContext.Provider value={contextData}>
{loading ? null : children}
</AuthContext.Provider>
);
};

18
src/auth/auth.js Normal file
View File

@ -0,0 +1,18 @@
import {useContext } from "react"
import React from 'react'
import AuthContext from "../auth/AuthContext";
import LoginPage from "../pages/UI/login/login";
import Header from "../components/header";
export const Auth = (props) => {
let {user} = useContext(AuthContext);
return (
(user.user_id)? <><Header />{props.component}</> : <LoginPage/>
)
}
export default Auth;

45
src/components/footer.js Normal file
View File

@ -0,0 +1,45 @@
import React from "react";
import config from "../global/GlobalJSON.json";
const Footer = () => {
const {
api: { version },
} = config;
return (
<div
style={{
backgroundColor: "#021526",
color: "white",
padding: "10px 20px",
textAlign: "center",
position: "fixed",
bottom: 0,
width: "100%",
boxShadow: "0 -2px 5px rgba(0, 0, 0, 0.2)",
zIndex: 0,
}}
>
<div className="container">
<p className="mb-0">
<span className="d-inline">
Developed by{" "}
<a
href="https://www.humbingo.com"
target="_blank"
rel="noopener noreferrer"
style={{ color: "inherit", textDecoration: "none" }}
>
Humbingo Consultancy Services
</a>
</span>
<span className="d-inline">
{" "}
| &copy; {new Date().getFullYear()} Cheque Print App. All rights
reserved.
</span>
<span className="d-inline"> | Version: {version}</span>
</p>
</div>
</div>
);
};
export default Footer;

View File

@ -0,0 +1,216 @@
// import React, { useState, useContext, useEffect } from "react";
// import {
// AppBar,
// Toolbar,
// Typography,
// Box,
// IconButton,
// Menu,
// MenuItem,
// useMediaQuery,
// Drawer,
// List,
// ListItem,
// ListItemText,
// } from "@mui/material";
// import { Link } from "react-router-dom";
// import AccountCircle from "@mui/icons-material/AccountCircle";
// import MenuIcon from "@mui/icons-material/Menu";
// import AuthContext from "../auth/AuthContext";
// import useApi from "../api-manager/useApi";
// import UserTypeUpdatePassword from "../utils/userTypePassword";
// const Header = () => {
// const { user, logOutUser } = useContext(AuthContext);
// const [profile, setProfile] = useState(null);
// const [userType, setUserType] = useState(null);
// const [companyName, setCompanyName] = useState("");
// const [companyId, setCompanyId] = useState(null);
// const [dialogOpen, setDialogOpen] = useState(false);
// const { Get, Post, getHost } = useApi();
// const isMobile = useMediaQuery("(max-width:600px)");
// const [drawerOpen, setDrawerOpen] = useState(false);
// const handleClose = () => {
// setProfile(null);
// };
// const handleMenu = (event) => {
// setProfile(event.currentTarget);
// };
// const toggleDrawer = (open) => (event) => {
// if (
// event.type === "keydown" &&
// (event.key === "Tab" || event.key === "Shift")
// ) {
// return;
// }
// setDrawerOpen(open);
// };
// const getUserType = async () => {
// try {
// const userTypeData = await Get("checkUserType");
// setUserType(userTypeData.user_type);
// const compId = await Get(
// `${getHost()}/api/v1/getCompanyByUserOrDeptId?user_id=${user.user_id}`
// );
// setCompanyName(compId.company_name);
// setCompanyId(compId.company_id);
// } catch (error) {
// setCompanyName("Hey Admin");
// }
// };
// useEffect(() => {
// getUserType();
// }, []);
// const renderLinks = () => {
// switch (userType) {
// case "department user":
// return [
// { path: "/", label: "Home" },
// { path: "/cheque-form", label: "Print Cheque" },
// { path: "/history", label: "Cheque History" },
// ];
// case "company user":
// return [
// { path: "/", label: "Home" },
// { path: "/cheque-form", label: "Print Cheque" },
// { path: "/history", label: "Cheque History" },
// { path: "/department", label: "Departments" },
// ];
// case "superuser":
// return [
// { path: "/", label: "Humbingo Home" },
// { path: "/company", label: "Company" },
// { path: "/AdminDepartment", label: "Departments" },
// { path: "/licence", label: "Licence" },
// { path: "/registree", label: "Registree" },
// { path: "/user", label: "User" },
// { path: "/role", label: "Role" },
// { path: "/history", label: "Cheque History" },
// ];
// default:
// return [];
// }
// };
// const linkStyle = {
// color: "inherit",
// textDecoration: "none",
// margin: "0 10px",
// };
// const drawerLinks = (
// <Box
// sx={{ width: 250 }}
// role="presentation"
// onClick={toggleDrawer(false)}
// onKeyDown={toggleDrawer(false)}
// >
// <List>
// {renderLinks().map((link, index) => (
// <ListItem button component={Link} to={link.path} key={index}>
// <ListItemText primary={link.label} />
// </ListItem>
// ))}
// </List>
// </Box>
// );
// const handlePasswordSubmit = async (newPassword) => {
// try {
// await Post(
// `${getHost()}/api/v1/updatePassword/company/${companyId}/`,
// { password: newPassword }
// );
// alert("Password updated successfully"); // Replace with a better toast notification if needed
// } catch (error) {
// console.error("Error changing password:", error);
// alert("Failed to update password"); // Replace with a better toast notification if needed
// }
// setDialogOpen(false);
// };
// return (
// <AppBar position="sticky" sx={{ backgroundColor: "#021526" }}>
// <Toolbar>
// <IconButton
// edge="start"
// color="inherit"
// aria-label="menu"
// onClick={toggleDrawer(true)}
// sx={{ display: isMobile ? "block" : "none" }}
// >
// <MenuIcon />
// </IconButton>
// <Typography
// variant="h6"
// sx={{ flexGrow: 1, display: "flex", alignItems: "center" }}
// >
// <img
// src="https://humbingo.com/wp-content/uploads/2024/06/Logo-32-.webp"
// height="50px"
// alt="Logo"
// />
// {!isMobile && (
// <span style={{ marginLeft: "10px" }}>{companyName}</span>
// )}
// </Typography>
// {!isMobile && (
// <Box sx={{ display: "flex" }}>
// {renderLinks().map((link, index) => (
// <Link to={link.path} style={linkStyle} key={index}>
// {link.label}
// </Link>
// ))}
// </Box>
// )}
// <IconButton
// edge="end"
// aria-label="account of current user"
// aria-haspopup="true"
// onClick={handleMenu}
// color="inherit"
// >
// <AccountCircle />
// </IconButton>
// <Menu
// anchorEl={profile}
// anchorOrigin={{
// vertical: "bottom",
// horizontal: "left",
// }}
// keepMounted
// transformOrigin={{
// vertical: "top",
// horizontal: "left",
// }}
// open={Boolean(profile)}
// onClose={handleClose}
// >
// {/* <MenuItem onClick={handleClose}>{`Hello, ${user.user_id}`}</MenuItem> */}
// <MenuItem onClick={() => setDialogOpen(true)}>Change Password</MenuItem>
// <MenuItem onClick={logOutUser} ><span style={{backgroundColor: "#f60002", color: "White", textAlign:"center",padding: "7px", width: "100%", borderRadius: "5px"}}>Logout</span></MenuItem>
// </Menu>
// </Toolbar>
// <Drawer anchor="left" open={drawerOpen} onClose={toggleDrawer(false)}>
// {drawerLinks}
// </Drawer>
// <UserTypeUpdatePassword
// open={dialogOpen}
// onClose={() => setDialogOpen(false)}
// onSubmit={handlePasswordSubmit}
// userType={userType}
// companyId={companyId}
// />
// </AppBar>
// );
// };
// export default Header;

280
src/components/header.js Normal file
View File

@ -0,0 +1,280 @@
import React, { useContext, useState } from 'react';
import {
AppBar,
Toolbar,
Typography,
IconButton,
Menu,
MenuItem,
Drawer,
CssBaseline,
List,
ListItem,
ListItemText,
Collapse,
Divider,
} from '@mui/material';
import { Link, useLocation } from 'react-router-dom';
import AuthContext from '../auth/AuthContext';
import {
Menu as MenuIcon,
ChevronLeft as ChevronLeftIcon,
ChevronRight as ChevronRightIcon,
ExpandLess,
ExpandMore,
Home as HomeIcon,
People as PeopleIcon,
CalendarToday as CalendarTodayIcon,
AccountBalance as AccountBalanceIcon,
Receipt as ReceiptIcon,
Paid as PaidIcon,
TimeToLeave as LeaveIcon,
Settings as SettingsIcon,
Help as HelpIcon,
} from '@mui/icons-material';
import { styled, useTheme } from '@mui/material/styles';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserCircle } from '@fortawesome/free-solid-svg-icons';
const drawerWidth = 240;
const Main = styled('main', { shouldForwardProp: (prop) => prop !== 'open' })(
({ theme, open }) => ({
flexGrow: 1,
padding: theme.spacing(3),
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
marginLeft: `-${drawerWidth}px`,
...(open && {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginLeft: 0,
}),
})
);
const AppBarStyled = styled(AppBar, {
shouldForwardProp: (prop) => prop !== 'open',
})(({ theme, open }) => ({
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
...(open && {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: `${drawerWidth}px`,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
}),
}));
const DrawerHeader = styled('div')(({ theme }) => ({
display: 'flex',
alignItems: 'center',
padding: theme.spacing(0, 1),
...theme.mixins.toolbar,
justifyContent: 'flex-end',
}));
const ListItemStyled = styled(ListItem)(({ theme }) => ({
'&.active': {
backgroundColor: theme.palette.action.hover,
},
}));
const Header = () => {
const { user, logOutUser } = useContext(AuthContext);
const [profileAnchorEl, setProfileAnchorEl] = useState(null);
const [drawerOpen, setDrawerOpen] = useState(false);
const [manageOpen, setManageOpen] = useState(false);
const [manageDataOpen, setManageDataOpen] = useState(false);
const theme = useTheme();
const location = useLocation();
const handleMenuOpen = (event) => {
setProfileAnchorEl(event.currentTarget);
};
const handleMenuClose = () => {
setProfileAnchorEl(null);
};
const handleLogout = () => {
logOutUser();
handleMenuClose();
};
const toggleDrawer = () => {
setDrawerOpen(!drawerOpen);
};
const toggleManageDropdown = () => {
setManageOpen(!manageOpen);
};
const toggleManageDataDropdown = () => {
setManageDataOpen(!manageDataOpen);
};
const handleNavClick = () => {
setDrawerOpen(false);
};
return (
<>
<CssBaseline />
<AppBarStyled position="fixed" open={drawerOpen} style={{ backgroundColor: '#35424a' }}>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={toggleDrawer}
edge="start"
sx={{ mr: 2, ...(drawerOpen && { display: 'none' }) }}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" noWrap component="div" sx={{ flexGrow: 1 }}>
HbaseApp
</Typography>
<IconButton edge="end" color="inherit" onClick={handleMenuOpen}>
<FontAwesomeIcon icon={faUserCircle} />
</IconButton>
<Menu
anchorEl={profileAnchorEl}
open={Boolean(profileAnchorEl)}
onClose={handleMenuClose}
>
<MenuItem onClick={handleMenuClose}>{`Hello, ${user?.user_id}`}</MenuItem>
<MenuItem onClick={handleLogout}>Logout</MenuItem>
</Menu>
</Toolbar>
</AppBarStyled>
<Drawer
sx={{
width: drawerWidth,
flexShrink: 0,
'& .MuiDrawer-paper': {
width: drawerWidth,
boxSizing: 'border-box',
},
}}
variant="persistent"
anchor="left"
open={drawerOpen}
>
<DrawerHeader>
<IconButton onClick={toggleDrawer}>
{theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />}
</IconButton>
</DrawerHeader>
<Divider />
<List>
<ListItemStyled
button
component={Link}
to="/"
onClick={handleNavClick}
className={location.pathname === '/' ? 'active' : ''}
>
<HomeIcon style={{ marginRight: '10px' }} />
<ListItemText primary="Home" />
</ListItemStyled>
<ListItemStyled button onClick={toggleManageDropdown}>
<ListItemText primary="Manage" />
{manageOpen ? <ExpandLess /> : <ExpandMore />}
</ListItemStyled>
<Collapse in={manageOpen} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
<ListItemStyled
button
component={Link}
to="/company"
onClick={handleNavClick}
sx={{ pl: 4 }}
className={location.pathname === '/company' ? 'active' : ''}
>
<AccountBalanceIcon style={{ marginRight: '10px' }} />
<ListItemText primary="Company" />
</ListItemStyled>
<ListItemStyled
button
component={Link}
to="/department"
onClick={handleNavClick}
sx={{ pl: 4 }}
className={location.pathname === '/department' ? 'active' : ''}
>
<PeopleIcon style={{ marginRight: '10px' }} />
<ListItemText primary="Department" />
</ListItemStyled>
<ListItemStyled
button
component={Link}
to="/employee"
onClick={handleNavClick}
sx={{ pl: 4 }}
className={location.pathname === '/employee' ? 'active' : ''}
>
<PeopleIcon style={{ marginRight: '10px' }} />
<ListItemText primary="Employee" />
</ListItemStyled>
</List>
</Collapse>
<ListItemStyled button onClick={toggleManageDataDropdown}>
<ListItemText primary="Manage Data" />
{manageDataOpen ? <ExpandLess /> : <ExpandMore />}
</ListItemStyled>
<Collapse in={manageDataOpen} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
<ListItemStyled
button
component={Link}
to="/rules"
onClick={handleNavClick}
sx={{ pl: 4 }}
className={location.pathname === '/rules' ? 'active' : ''}
>
<SettingsIcon style={{ marginRight: '10px' }} />
<ListItemText primary="Rules" />
</ListItemStyled>
</List>
</Collapse>
<Divider />
<ListItemStyled
button
component={Link}
to="/setting"
onClick={handleNavClick}
className={location.pathname === '/setting' ? 'active' : ''}
>
<SettingsIcon style={{ marginRight: '10px' }} />
<ListItemText primary="Setting" />
</ListItemStyled>
<ListItemStyled
button
component={Link}
to="/su"
onClick={handleNavClick}
className={location.pathname === '/su' ? 'active' : ''}
>
<HelpIcon style={{ marginRight: '10px' }} />
<ListItemText primary="Support" />
</ListItemStyled>
</List>
</Drawer>
<Main open={drawerOpen}>
<DrawerHeader />
</Main>
</>
);
};
export default Header;

9
src/global/Global.js Normal file
View File

@ -0,0 +1,9 @@
import global from "../global/GlobalJSON.json"
export function getAPI(API_NAME) {
return global.api.host + global.api[API_NAME];
}
export function getHost() {
return global.api.host;
}

View File

@ -0,0 +1,14 @@
{
"api": {
"host": "https://cheque-api.humbingo.in",
"token": "/auth/token/",
"refreshToken": "/auth/token/refresh/",
"user": "/api/v1/user/",
"role": "/api/v1/role/",
"permission": "/api/v1/permission/",
"checkUserType": "/api/v1/checkUserType",
"version": "1.0"
},
"debug": true
}

BIN
src/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

12
src/pages/UI/home/home.js Normal file
View File

@ -0,0 +1,12 @@
import React from "react";
function Home() {
return (
<div>
<h1>Home Page</h1>
</div>
);
}
export default Home;

121
src/pages/UI/login/login.js Normal file
View File

@ -0,0 +1,121 @@
import React, { useContext, useEffect, useState } from "react";
import AuthContext from "../../../auth/AuthContext";
import { Link, useNavigate } from "react-router-dom";
import {
Container,
TextField,
Typography,
Paper,
Button,
Grid,
IconButton,
InputAdornment,
} from "@mui/material";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import logo from "../../../logo.png"
const LoginPage = () => {
let { loginUser } = useContext(AuthContext);
let { authToken } = useContext(AuthContext);
const [showPassword, setShowPassword] = useState(false);
let navigate = useNavigate();
let checkLogedIn = () => {
if (authToken) {
navigate("/");
} else {
console.error("Unable to check authToken");
return false;
}
};
const handleClickShowPassword = () => {
setShowPassword((prev) => !prev);
};
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
useEffect(() => {
checkLogedIn();
}, [authToken]);
return (
<div>
<form onSubmit={loginUser}>
<Container component="main" maxWidth="xs">
<Paper
elevation={3}
sx={{
marginTop: 8,
padding: 4,
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
{/* Logo */}
<img
src={`${logo}`}
alt="Logo"
style={{ height: 100, width: 150, marginBottom: 20 }} // Adjust size and margin as needed
/>
<h1 style={{ fontFamily: "consolas" }}>
</h1>
<Typography component="h1" variant="h5">
Login
</Typography>
<TextField
margin="normal"
required
fullWidth
name="username"
label="User Name"
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type={showPassword ? "text" : "password"}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
edge="end"
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<br />
<Button
variant="contained"
color="primary"
fullWidth
type="Submit"
name="submit"
>
Login
</Button>
</Paper>
</Container>
</form>
</div>
);
};
export default LoginPage;

View File

@ -0,0 +1,56 @@
import React, { useState } from "react";
import {
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
Button,
} from "@mui/material";
const UserTypeUpdatePassword = ({
open,
onClose,
onSubmit,
userType,
companyId,
departmentId,
}) => {
const [newPassword, setNewPassword] = useState("");
const handleSubmit = () => {
if (!newPassword) {
alert("Please enter a new password");
return;
}
// Determine which ID to use based on userType
const id = userType === "company user" ? companyId : departmentId;
if (!id) {
alert("ID not found");
return;
}
onSubmit(newPassword);
setNewPassword(""); // Clear the input after submission
};
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>Change Password</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
id="password"
label="New Password"
type="password"
fullWidth
variant="standard"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleSubmit} variant="contained">Change Password</Button>
</DialogActions>
</Dialog>
);
};
export default UserTypeUpdatePassword;

View File

@ -1,70 +0,0 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

View File

@ -1,25 +0,0 @@
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;