@campxdev/campx-web-utils 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env ADDED
@@ -0,0 +1,2 @@
1
+ REACT_APP_API_HOST=https://api.campx.dev
2
+ PORT=3082
@@ -0,0 +1,25 @@
1
+ const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
2
+
3
+ const path = require("path");
4
+ const deps = require("./package.json").dependencies;
5
+ const { getLoader, loaderByName } = require("@craco/craco");
6
+ const packages = [];
7
+ packages.push(path.dirname(require.resolve("@campxdev/react-blueprint")));
8
+ module.exports = {
9
+ webpack: {
10
+ configure: (webpackConfig) => {
11
+ const { isFound, match } = getLoader(
12
+ webpackConfig,
13
+ loaderByName("babel-loader")
14
+ );
15
+ if (isFound) {
16
+ const include = Array.isArray(match.loader.include)
17
+ ? match.loader.include
18
+ : [match.loader.include];
19
+ match.loader.include = include.concat(packages);
20
+ }
21
+
22
+ return webpackConfig;
23
+ },
24
+ },
25
+ };
package/exports.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from "./src/config/axios";
2
+ export * from "./src/ErrorBoundary/export";
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@campxdev/campx-web-utils",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "main": "./exports.ts",
5
5
  "private": false,
6
6
  "dependencies": {
7
- "@campxdev/react-blueprint": "^0.1.41",
7
+ "@campxdev/react-blueprint": "^1.0.14",
8
+ "@mui/x-date-pickers": "^7.11.0",
8
9
  "@testing-library/jest-dom": "^5.14.1",
9
10
  "@testing-library/react": "^13.0.0",
10
11
  "@testing-library/user-event": "^13.2.1",
11
- "react-toastify": "^9.0.1",
12
12
  "@types/jest": "^27.0.1",
13
13
  "@types/node": "^16.7.13",
14
14
  "@types/react": "^18.0.0",
@@ -18,17 +18,32 @@
18
18
  "pullstate": "^1.25.0",
19
19
  "react": "^18.3.1",
20
20
  "react-dom": "^18.3.1",
21
+ "react-query": "^3.39.3",
21
22
  "react-scripts": "5.0.1",
23
+ "react-toastify": "^9.0.1",
22
24
  "typescript": "^4.4.2",
23
25
  "web-vitals": "^2.1.0"
24
26
  },
25
27
  "devDependencies": {
26
- "@types/js-cookie": "^3.0.2"
28
+ "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
29
+ "@craco/craco": "^7.1.0",
30
+ "@types/babel__core": "^7.20.5",
31
+ "@types/babel__generator": "^7.6.8",
32
+ "@types/babel__template": "^7.4.4",
33
+ "@types/babel__traverse": "^7.20.6",
34
+ "@types/bonjour": "^3.5.13",
35
+ "@types/js-cookie": "^3.0.2",
36
+ "@types/lodash": "^4.17.5",
37
+ "@types/prettier": "^3.0.0",
38
+ "@types/react": "^18.3.3",
39
+ "@types/react-dom": "^18.3.0",
40
+ "@types/react-query": "^1.2.9",
41
+ "@types/react-router-dom": "^5.3.3"
27
42
  },
28
43
  "scripts": {
29
- "start": "react-scripts start",
30
- "build": "react-scripts build",
31
- "test": "react-scripts test",
44
+ "start": "craco start",
45
+ "build": "craco build",
46
+ "test": "craco test",
32
47
  "eject": "react-scripts eject"
33
48
  },
34
49
  "eslintConfig": {
package/src/App.tsx CHANGED
@@ -1,26 +1,15 @@
1
- import React from 'react';
2
- import logo from './logo.svg';
3
- import './App.css';
1
+ import { useRoutes } from "react-router-dom";
2
+ import Providers from "./context/Providers";
3
+ import { mainRoutes } from "./Pages/main";
4
4
 
5
- function App() {
5
+ export default function App() {
6
6
  return (
7
- <div className="App">
8
- <header className="App-header">
9
- <img src={logo} className="App-logo" alt="logo" />
10
- <p>
11
- Edit <code>src/App.tsx</code> and save to reload.
12
- </p>
13
- <a
14
- className="App-link"
15
- href="https://reactjs.org"
16
- target="_blank"
17
- rel="noopener noreferrer"
18
- >
19
- Learn React
20
- </a>
21
- </header>
22
- </div>
7
+ <Providers>
8
+ <AppRouter />
9
+ </Providers>
23
10
  );
24
11
  }
25
-
26
- export default App;
12
+ const AppRouter = () => {
13
+ const app = useRoutes(mainRoutes);
14
+ return app;
15
+ };
@@ -0,0 +1,37 @@
1
+ import { useQuery } from "react-query";
2
+ import { axios } from "./config/axios";
3
+
4
+ const fetchClubRequests = () => {
5
+ return axios
6
+ .get(`/hrms/departments`, {
7
+ headers: {
8
+ "x-tenant-id": "aupulse",
9
+ "X-Institution-Code": "aupulse",
10
+ campx_session_key: "66a36c752e28b1200876b034",
11
+ },
12
+ })
13
+ .then((res) => res.data);
14
+ };
15
+
16
+ function AppContent() {
17
+ const {
18
+ data: requests,
19
+ isLoading,
20
+ error,
21
+ refetch,
22
+ } = useQuery("club-requests", () => fetchClubRequests());
23
+
24
+ if (isLoading) {
25
+ return <div>Loading...</div>;
26
+ }
27
+
28
+ // if (error) {
29
+ // // No need to handle the error locally, it will be caught by ErrorBoundary
30
+ // console.error("Error fetching club requests:", error);
31
+ // throw error; // Re-throw the error to be caught by the ErrorBoundary
32
+ // }
33
+
34
+ return <></>;
35
+ }
36
+
37
+ export default AppContent;
@@ -0,0 +1,125 @@
1
+ import { InternalServerError } from "@campxdev/react-blueprint/src/components/Assets/ErrorPages/InternalServerError";
2
+ import { NoInterneConnection } from "@campxdev/react-blueprint/src/components/Assets/ErrorPages/NoInternetConnection";
3
+ import { UnAuthorized } from "@campxdev/react-blueprint/src/components/Assets/ErrorPages/UnAuthorized";
4
+ import { Button } from "@campxdev/react-blueprint/src/components/Input/Button/Button";
5
+ import { Alert, Box, styled } from "@mui/material";
6
+ import Cookies from "js-cookie";
7
+ import { ReactNode } from "react";
8
+ import { ErrorBoundary as ReactErrorBoundary } from "react-error-boundary";
9
+ import { QueryErrorResetBoundary } from "react-query";
10
+ import { useLocation, useNavigate } from "react-router-dom";
11
+ import { axios } from "../config/axios";
12
+
13
+ export type ErrorBoundaryProps = {
14
+ children: ReactNode;
15
+ resetKey?: string;
16
+ };
17
+
18
+ const StyledAlert = styled(Alert)(({ theme }) => ({
19
+ height: "60px",
20
+ border: `1px solid ${theme.palette.error.main}`,
21
+ display: "flex",
22
+ alignItems: "center",
23
+ "& .MuiAlert-message": {
24
+ padding: 0,
25
+ },
26
+ "& .MuiTypography-root": {
27
+ margin: 0,
28
+ },
29
+ position: "relative",
30
+ "& .retryBtn": {
31
+ color: "#661B2A",
32
+ position: "absolute",
33
+ right: 8,
34
+ top: 8,
35
+ },
36
+ }));
37
+
38
+ export const ErrorBoundary = (props: ErrorBoundaryProps) => {
39
+ const location = useLocation();
40
+ return (
41
+ <QueryErrorResetBoundary>
42
+ {({ reset }) => (
43
+ <ReactErrorBoundary
44
+ key={location?.pathname}
45
+ onReset={reset}
46
+ FallbackComponent={ErrorFallback}
47
+ >
48
+ {props.children}
49
+ </ReactErrorBoundary>
50
+ )}
51
+ </QueryErrorResetBoundary>
52
+ );
53
+ };
54
+
55
+ export const ErrorFallback = ({ error, resetErrorBoundary }: any) => {
56
+ console.log(error, "llll");
57
+ if (error?.response?.status) {
58
+ switch (error?.response?.status) {
59
+ case 401:
60
+ return <UnAuth resetErrorBoundary={resetErrorBoundary} />;
61
+
62
+ case 500:
63
+ return <InternalServerError resetBoundary={resetErrorBoundary} />;
64
+ }
65
+ }
66
+
67
+ if (error?.code === "ERR_NETWORK") {
68
+ return <NoInterneConnection resetBoundary={resetErrorBoundary} />;
69
+ }
70
+
71
+ return (
72
+ <Box sx={{ marginTop: "16px", padding: "20px" }}>
73
+ <StyledAlert severity="error">
74
+ {error?.response?.data?.message ?? error?.message}
75
+ <Button
76
+ className="retryBtn"
77
+ onClick={() => resetErrorBoundary()}
78
+ size="small"
79
+ color="error"
80
+ variant="outlined"
81
+ >
82
+ Try Again
83
+ </Button>
84
+ </StyledAlert>
85
+ </Box>
86
+ );
87
+ };
88
+
89
+ const UnAuth = ({ resetBoundary }: any) => {
90
+ const navigate = useNavigate();
91
+
92
+ const sessionCookie = Cookies.get("campx_session_key");
93
+
94
+ const appinit = async () => {
95
+ await axios.get("/auth/my-permissions").catch((e: any) => {
96
+ navigate("/auth/login");
97
+ });
98
+ };
99
+
100
+ const handleLoginClick = () => {
101
+ if (!sessionCookie) {
102
+ navigate("/auth/login");
103
+ } else {
104
+ appinit();
105
+ }
106
+ };
107
+
108
+ return (
109
+ <UnAuthorized
110
+ component={
111
+ <>
112
+ <Button
113
+ sx={{
114
+ marginTop: "20px",
115
+ }}
116
+ variant="contained"
117
+ onClick={handleLoginClick}
118
+ >
119
+ Click Here To Login
120
+ </Button>
121
+ </>
122
+ }
123
+ />
124
+ );
125
+ };
@@ -0,0 +1,13 @@
1
+ import { LinearProgress } from "@mui/material";
2
+ import { Store } from "pullstate";
3
+
4
+ export const NetworkStore = new Store({
5
+ loading: false,
6
+ });
7
+
8
+ export default function GlobalNetworkLoadingIndicator() {
9
+ const { loading } = NetworkStore.useState();
10
+
11
+ if (loading) return <LinearProgress />;
12
+ if (loading) return null;
13
+ }
@@ -0,0 +1 @@
1
+ export * from "./ErrorBoundary";
@@ -0,0 +1,11 @@
1
+ import { Outlet } from "react-router-dom";
2
+
3
+ const AppLayout = () => {
4
+ return (
5
+ <>
6
+ <Outlet />
7
+ </>
8
+ );
9
+ };
10
+
11
+ export default AppLayout;
@@ -0,0 +1,20 @@
1
+ import { Navigate } from "react-router-dom";
2
+ import AppContent from "../AppContent";
3
+ import AppLayout from "../Layout/AppLayout";
4
+
5
+ export const mainRoutes = [
6
+ {
7
+ path: "/",
8
+ element: <AppLayout />,
9
+ children: [
10
+ {
11
+ index: true,
12
+ element: <Navigate to={"app-content"} />,
13
+ },
14
+ {
15
+ path: "app-content",
16
+ element: <AppContent />,
17
+ },
18
+ ],
19
+ },
20
+ ];
@@ -1,15 +1,22 @@
1
- import Axios from "axios";
1
+ import Axios, { InternalAxiosRequestConfig } from "axios";
2
2
  import Cookies from "js-cookie";
3
+ import { SnackbarStore } from "../context/SnackbarProvider";
3
4
 
4
5
  const isDevelopment = process.env.NODE_ENV == "development";
5
6
 
6
- const sessionKey = Cookies.get("campx_session_key");
7
7
  const tenantCode = isDevelopment
8
8
  ? Cookies.get("campx_tenant")
9
9
  : window.location.hostname.split(".")[0];
10
10
  const institutionCode = window.location.pathname.split("/")[1];
11
11
 
12
- const openPaymentsKey = Cookies.get("campx_open_payments_key");
12
+ export const formatParams = (params: any) => {
13
+ return Object.fromEntries(
14
+ Object.entries(params ?? {})?.map((i) => [
15
+ i[0],
16
+ i[1] === "__empty__" ? "" : i[1],
17
+ ])
18
+ );
19
+ };
13
20
 
14
21
  export const axios = Axios.create({
15
22
  baseURL: process.env.REACT_APP_API_HOST,
@@ -17,9 +24,60 @@ export const axios = Axios.create({
17
24
  headers: {
18
25
  "x-tenant-id": tenantCode,
19
26
  "x-institution-code": institutionCode,
20
- campx_session_key: sessionKey,
21
- ...(openPaymentsKey && {
22
- campx_open_payments_key: openPaymentsKey,
23
- }),
24
27
  },
25
28
  });
29
+
30
+ axios.interceptors.request.use(
31
+ function (config: InternalAxiosRequestConfig) {
32
+ const params = formatParams(config?.params);
33
+
34
+ const sessionKey = Cookies.get("campx_session_key");
35
+ const openPaymentsKey = Cookies.get("campx_open_payments_key");
36
+
37
+ if (isDevelopment && sessionKey) {
38
+ config.headers.set("campx_session_key", sessionKey);
39
+ }
40
+
41
+ if (openPaymentsKey) {
42
+ config.headers.set("campx_open_payments_key", openPaymentsKey);
43
+ }
44
+
45
+ return {
46
+ ...config,
47
+ params,
48
+ };
49
+ },
50
+ function (error) {
51
+ return Promise.reject(error);
52
+ }
53
+ );
54
+
55
+ axios.interceptors.response.use(
56
+ function (response) {
57
+ console.log(response);
58
+ if (
59
+ response.config.method &&
60
+ ["put", "post", "delete", "patch"].includes(response.config.method) &&
61
+ [200, 202].includes(response.status)
62
+ ) {
63
+ SnackbarStore.update((s) => {
64
+ s.open = true;
65
+ s.message = response.data.message;
66
+ s.variant = "success";
67
+ });
68
+ }
69
+
70
+ return response;
71
+ },
72
+ function (err) {
73
+ if ([400, 404, 422].includes(err.response.status)) {
74
+ SnackbarStore.update((s) => {
75
+ s.open = true;
76
+ s.message = err.response.data.message || "Bad Request";
77
+ s.variant = "alert";
78
+ });
79
+ }
80
+
81
+ return Promise.reject(err);
82
+ }
83
+ );
@@ -0,0 +1,32 @@
1
+ import { MuiThemeProvider } from "@campxdev/react-blueprint";
2
+ import { ReactNode } from "react";
3
+ import { QueryClient, QueryClientProvider } from "react-query";
4
+ import { BrowserRouter } from "react-router-dom";
5
+ import { ErrorBoundary } from "../ErrorBoundary/ErrorBoundary";
6
+ import { SnackbarProvider } from "./SnackbarProvider";
7
+
8
+ export const queryClient = new QueryClient({
9
+ defaultOptions: {
10
+ queries: {
11
+ refetchOnWindowFocus: false,
12
+ retry: false,
13
+ useErrorBoundary: true,
14
+ },
15
+ },
16
+ });
17
+
18
+ export default function Providers({ children }: { children: ReactNode }) {
19
+ var baseName = "/";
20
+
21
+ return (
22
+ <BrowserRouter basename={baseName}>
23
+ <QueryClientProvider client={queryClient}>
24
+ <MuiThemeProvider>
25
+ <SnackbarProvider>
26
+ <ErrorBoundary>{children}</ErrorBoundary>
27
+ </SnackbarProvider>
28
+ </MuiThemeProvider>
29
+ </QueryClientProvider>
30
+ </BrowserRouter>
31
+ );
32
+ }
@@ -0,0 +1,49 @@
1
+ import { Snackbar } from "@campxdev/react-blueprint";
2
+ import { Store } from "pullstate";
3
+ import { createContext, ReactNode } from "react";
4
+
5
+ type Variant = "success" | "info" | "warning" | "alert";
6
+
7
+ interface SnackbarContextProps {
8
+ showSnackbar: (message: string, variant?: Variant) => void;
9
+ }
10
+
11
+ const SnackbarContext = createContext<SnackbarContextProps | undefined>(
12
+ undefined
13
+ );
14
+
15
+ interface SnackbarProviderProps {
16
+ children: ReactNode;
17
+ }
18
+ export const SnackbarStore = new Store({
19
+ open: false,
20
+ message: "",
21
+ variant: "success" as Variant,
22
+ });
23
+
24
+ export const SnackbarProvider = ({ children }: SnackbarProviderProps) => {
25
+ const snackbar = SnackbarStore.useState((s) => s);
26
+ const showSnackbar = (message: string, variant: Variant = "info") => {
27
+ SnackbarStore.update((s) => {
28
+ s.open = true;
29
+ s.message = message;
30
+ s.variant = variant;
31
+ });
32
+ };
33
+ return (
34
+ <SnackbarContext.Provider value={{ showSnackbar }}>
35
+ {children}
36
+ <Snackbar
37
+ open={snackbar.open}
38
+ message={snackbar.message}
39
+ variant={snackbar.variant}
40
+ autoHideDuration={1500}
41
+ onClose={() => {
42
+ SnackbarStore.update((s) => {
43
+ s.open = false;
44
+ });
45
+ }}
46
+ />
47
+ </SnackbarContext.Provider>
48
+ );
49
+ };
package/tsconfig.json CHANGED
@@ -21,6 +21,10 @@
21
21
  "jsx": "react-jsx"
22
22
  },
23
23
  "include": [
24
- "src"
24
+ "src",
25
+ "./types"
26
+ ],
27
+ "exclude": [
28
+ "node_modules"
25
29
  ]
26
30
  }
@@ -0,0 +1,58 @@
1
+ import "@mui/material/styles";
2
+
3
+ declare module "@mui/material/styles" {
4
+ interface Theme {
5
+ palette: {
6
+ [x: string]: any;
7
+ primary: {
8
+ dark: string;
9
+ main: string;
10
+ light: string;
11
+ };
12
+ secondary: {
13
+ main: string;
14
+ light: string;
15
+ dark: string;
16
+ };
17
+ tertiary: {
18
+ main: string;
19
+ };
20
+ text: {
21
+ primary: string;
22
+ secondary: string;
23
+ tertiary: string;
24
+ };
25
+ surface: {
26
+ defaultBackground: string;
27
+ paperBackground: string;
28
+ grey: string;
29
+ };
30
+ border: {
31
+ primary: string;
32
+ };
33
+ highlight: {
34
+ highlightGreen: string;
35
+ highlightOrange: string;
36
+ highlightBlue: string;
37
+ highlightRed: string;
38
+ highlightPink: string;
39
+ highlightYellow: string;
40
+ greenBackground: string;
41
+ orangeBackground: string;
42
+ blueBackground: string;
43
+ redBackground: string;
44
+ pinkBackground: string;
45
+ yellowBackground: string;
46
+ };
47
+ };
48
+ }
49
+ export function createTheme(options?: CustomThemeOptions): CustomTheme;
50
+ }
51
+
52
+ declare module "@mui/material/Typography" {
53
+ interface TypographyPropsVariantOverrides {
54
+ label1: true;
55
+ label2: true;
56
+ subtitle3: true;
57
+ }
58
+ }
package/src/App.test.tsx DELETED
@@ -1,9 +0,0 @@
1
- import React from 'react';
2
- import { render, screen } from '@testing-library/react';
3
- import App from './App';
4
-
5
- test('renders learn react link', () => {
6
- render(<App />);
7
- const linkElement = screen.getByText(/learn react/i);
8
- expect(linkElement).toBeInTheDocument();
9
- });