@syzy/apphost 1.0.17 → 1.0.19
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/dist/App.d.ts +2 -2
- package/dist/App.js +48 -6
- package/dist/api/mapping-api.js +6 -6
- package/dist/components/Login/Login.js +6 -3
- package/dist/components/Mappings/ComponentMapping/ComponentRoleMapping.js +7 -12
- package/dist/components/SettingsPage/SettingsPage.d.ts +3 -0
- package/dist/components/SettingsPage/SettingsPage.js +240 -0
- package/dist/components/api/settings-api.d.ts +26 -0
- package/dist/components/api/settings-api.js +131 -0
- package/dist/config/EnvConfig.d.ts +4 -6
- package/dist/config/EnvConfig.js +4 -6
- package/dist/hoc/withSyzyAuth.d.ts +1 -0
- package/dist/hoc/withSyzyAuth.js +86 -0
- package/dist/hooks/useCurrentUser.d.ts +3 -0
- package/dist/hooks/useCurrentUser.js +6 -0
- package/dist/hooks/useDispatch.d.ts +3 -0
- package/dist/hooks/useDispatch.js +7 -0
- package/dist/hooks/usePermission.d.ts +1 -0
- package/dist/hooks/usePermission.js +7 -0
- package/dist/main.js +2 -2
- package/dist/services/Storage-service.d.ts +2 -0
- package/dist/services/Storage-service.js +26 -0
- package/dist/store/AppAction.d.ts +11 -0
- package/dist/store/AppAction.js +5 -0
- package/dist/store/AppContext.d.ts +3 -0
- package/dist/store/AppContext.js +3 -0
- package/dist/store/AppContextType.d.ts +12 -0
- package/dist/store/AppContextType.js +6 -0
- package/dist/store/AppProvider.d.ts +7 -0
- package/dist/store/AppProvider.js +32 -0
- package/dist/store/HostedInContainerContext.d.ts +5 -0
- package/dist/store/HostedInContainerContext.js +11 -0
- package/dist/store/SesssionReducer.d.ts +4 -0
- package/dist/store/SesssionReducer.js +16 -0
- package/package.json +1 -1
package/dist/App.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
export declare const componentMap: Record<string, React.ComponentType<any>>;
|
|
3
|
-
declare
|
|
4
|
-
export default
|
|
3
|
+
declare const _default: (props: any) => import("react/jsx-runtime").JSX.Element;
|
|
4
|
+
export default _default;
|
package/dist/App.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
import { jsx as _jsx,
|
|
2
|
-
import
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
// import { configureAmplify } from "./config/amplifyConfig.ts";
|
|
3
|
+
import { Route, Routes } from 'react-router-dom';
|
|
4
|
+
import { useCurrentUser } from './hooks/useCurrentUser';
|
|
5
|
+
import { withSyzyAuth } from './hoc/withSyzyAuth';
|
|
6
|
+
import React, { useState } from 'react';
|
|
3
7
|
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
|
|
4
|
-
import LoadingSpinner from './components/Loader/Loader';
|
|
5
|
-
import Home from './components/Home/Home';
|
|
6
8
|
import BranchMapping from './components/Mappings/BranchMapping/Branch';
|
|
7
9
|
import MappingFormBranchUser from './components/Mappings/BranchMapping/MappingFormBranchUser';
|
|
8
10
|
import ComponentRoleMapping from './components/Mappings/ComponentMapping/ComponentRoleMapping';
|
|
9
11
|
import MappingFormUserRole from './components/Mappings/RoleMapping/MappingFormUserRole';
|
|
12
|
+
import Home from './components/Home/Home';
|
|
13
|
+
import LoadingSpinner from './components/Loader/Loader';
|
|
14
|
+
// import { isHostedInContainer } from "./util/hostedinContainer.ts";
|
|
15
|
+
// configureAmplify();
|
|
10
16
|
export const componentMap = {
|
|
11
17
|
BranchMapping,
|
|
12
18
|
MappingFormBranchUser,
|
|
@@ -14,7 +20,43 @@ export const componentMap = {
|
|
|
14
20
|
ComponentRoleMapping,
|
|
15
21
|
Home,
|
|
16
22
|
};
|
|
23
|
+
const flattenRoutes = (items) => {
|
|
24
|
+
const flat = [];
|
|
25
|
+
const walk = (arr) => {
|
|
26
|
+
arr.forEach(item => {
|
|
27
|
+
if (item.path && item.requiredComponent) {
|
|
28
|
+
flat.push(item);
|
|
29
|
+
}
|
|
30
|
+
if (item.children) {
|
|
31
|
+
walk(item.children);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
walk(items);
|
|
36
|
+
return flat;
|
|
37
|
+
};
|
|
38
|
+
const withAccessControl = (Component, props, requiredComponent, allowedComponents) => {
|
|
39
|
+
// Check if the user has access
|
|
40
|
+
const isAllowed = !requiredComponent || (allowedComponents?.includes(requiredComponent));
|
|
41
|
+
if (!isAllowed) {
|
|
42
|
+
return () => (_jsx("div", { className: "text-center mt-5", children: _jsx("h3", { className: "text-danger", children: "You are not allowed to see this page." }) }));
|
|
43
|
+
}
|
|
44
|
+
return () => _jsx(Component, { ...props });
|
|
45
|
+
};
|
|
17
46
|
function App({ isSessionReady }) {
|
|
18
|
-
|
|
47
|
+
const { user } = useCurrentUser();
|
|
48
|
+
const [routes, setRoutes] = useState([]);
|
|
49
|
+
const flatRoutes = flattenRoutes(routes);
|
|
50
|
+
// useEffect(() => {
|
|
51
|
+
// isHostedInContainer();
|
|
52
|
+
// configureAmplify();
|
|
53
|
+
// }, []);
|
|
54
|
+
return (_jsxs(_Fragment, { children: [_jsx("div", { style: { display: "flex", width: "100%" }, children: _jsx("div", { style: { flex: 1, padding: "10px" }, children: !isSessionReady ? (_jsx(LoadingSpinner, {})) : (_jsx(React.Fragment, { children: _jsxs(Routes, { children: [flatRoutes.map(({ path, requiredComponent, props }) => {
|
|
55
|
+
const PageComponent = componentMap[requiredComponent];
|
|
56
|
+
if (!PageComponent)
|
|
57
|
+
return null;
|
|
58
|
+
const ProtectedComponent = withAccessControl(PageComponent, props, requiredComponent, user.allowedComponents);
|
|
59
|
+
return _jsx(Route, { path: path, element: _jsx(ProtectedComponent, {}) }, path);
|
|
60
|
+
}), _jsx(Route, { path: "*", element: _jsx("h3", { className: "text-danger", children: "Page Not Found" }) })] }) })) }) }), _jsx(ReactQueryDevtools, { initialIsOpen: false })] }));
|
|
19
61
|
}
|
|
20
|
-
export default App;
|
|
62
|
+
export default withSyzyAuth(App);
|
package/dist/api/mapping-api.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
2
|
+
import { EnvConfig } from "../config/EnvConfig";
|
|
3
|
+
import { Client } from "../services/Client.Service";
|
|
2
4
|
import { initUserMappingDto, transformtoUserMappingDto } from "../domain/model/UserMappingDto";
|
|
3
5
|
import { initRoleMappingDto, transformtoRoleMappingDto } from "../domain/model/RoleMappingDto";
|
|
4
6
|
import { initComponentMappingDto, transformtoComponentMappingDto } from "../domain/model/ComponentMappingDto";
|
|
@@ -9,12 +11,10 @@ import { logger } from "../util/Logger";
|
|
|
9
11
|
import { createBranchMutationGQL, createMapping, updateMapping } from "../customGraphQL/customMutations";
|
|
10
12
|
import { listBranchesQuery, ListBranchUserMappings, ListComponentRoleMappings, listMapping, ListUserRoleMapping, updateBranchMutationQuery } from "../customGraphQL/customQueries";
|
|
11
13
|
import { Status } from "../domain/type/StatusEnum";
|
|
12
|
-
import { Client } from "../services/Client.Service";
|
|
13
|
-
import { EnvConfig } from "../config/EnvConfig";
|
|
14
14
|
export const MAPPING_RESOURCE = "mapping";
|
|
15
15
|
export const GET_MAPPING_BY_USERID_QUERYKEY = "mappingbyuserid";
|
|
16
16
|
export const LIST_BRANCHES_RESOURCE = "branches";
|
|
17
|
-
const endpoint = EnvConfig.
|
|
17
|
+
const endpoint = EnvConfig.appHostAPi;
|
|
18
18
|
export const transformtoMappingDto = (mappingData) => {
|
|
19
19
|
logger.info("transform to MappingDto:", mappingData);
|
|
20
20
|
const { __typename, createdAt, updatedAt, ...itm } = mappingData;
|
|
@@ -367,7 +367,7 @@ export const useUpdateBranchMutation = () => {
|
|
|
367
367
|
});
|
|
368
368
|
};
|
|
369
369
|
export const fetchBranchUserMappings = async (branchesMap) => {
|
|
370
|
-
const endpoint = EnvConfig.
|
|
370
|
+
const endpoint = EnvConfig.appHostAPi;
|
|
371
371
|
const client = await Client.getCustomGraphqlClient(endpoint);
|
|
372
372
|
const response = await client.request(ListBranchUserMappings);
|
|
373
373
|
return response.listMapping.map((m) => {
|
|
@@ -385,7 +385,7 @@ export const fetchBranchUserMappings = async (branchesMap) => {
|
|
|
385
385
|
});
|
|
386
386
|
};
|
|
387
387
|
export const fetchUserRoleMappings = async () => {
|
|
388
|
-
const endpoint = EnvConfig.
|
|
388
|
+
const endpoint = EnvConfig.appHostAPi;
|
|
389
389
|
const client = await Client.getCustomGraphqlClient(endpoint);
|
|
390
390
|
const response = await client.request(ListUserRoleMapping);
|
|
391
391
|
return response.listMapping.map(m => ({
|
|
@@ -402,7 +402,7 @@ export const useUserRoleMappings = () => {
|
|
|
402
402
|
});
|
|
403
403
|
};
|
|
404
404
|
export const fetchComponentRoleMappings = async () => {
|
|
405
|
-
const client = await Client.getCustomGraphqlClient(EnvConfig.
|
|
405
|
+
const client = await Client.getCustomGraphqlClient(EnvConfig.appHostAPi);
|
|
406
406
|
const response = await client.request(ListComponentRoleMappings);
|
|
407
407
|
return response.listMapping.map((m) => {
|
|
408
408
|
const transformed = transformtoMappingDto(m);
|
|
@@ -6,15 +6,17 @@ import { toast } from "react-toastify";
|
|
|
6
6
|
import "react-toastify/dist/ReactToastify.css";
|
|
7
7
|
import { useNavigate } from "react-router-dom";
|
|
8
8
|
import { FaEye, FaEyeSlash } from "react-icons/fa";
|
|
9
|
-
|
|
9
|
+
import logo from "../../../src/assets/images/Hotel-Logo.jpg";
|
|
10
10
|
import { signIn, signUp, confirmSignUp, confirmResetPassword, getCurrentUser, confirmSignIn, resetPassword } from "aws-amplify/auth";
|
|
11
11
|
import { signInSchema, registerSchema, confirmSignUpSchema, resetPasswordSchema, forceResetSchema, forgotPasswordSchema, } from "./loginSchema";
|
|
12
|
+
import { ALL, HIDE_SIGN_UP, HIDE_SIGN_UP_IS_NO } from "../../static/constants";
|
|
13
|
+
import { useGetSettingsByPkAndSk } from "../api/settings-api";
|
|
12
14
|
const LoginForm = ({ login }) => {
|
|
13
15
|
const [authMode, setAuthMode] = useState("signin");
|
|
14
16
|
const navigate = useNavigate();
|
|
15
17
|
const [tempUsername, setTempUsername] = useState("");
|
|
16
18
|
const [showPassword, setShowPassword] = useState(false);
|
|
17
|
-
|
|
19
|
+
const { settingsByPkAndSk } = useGetSettingsByPkAndSk(ALL, HIDE_SIGN_UP);
|
|
18
20
|
const getSchema = () => {
|
|
19
21
|
switch (authMode) {
|
|
20
22
|
case "signin":
|
|
@@ -141,6 +143,7 @@ const LoginForm = ({ login }) => {
|
|
|
141
143
|
const isPassword = type === "password";
|
|
142
144
|
return (_jsxs("div", { className: "mb-3 position-relative", children: [_jsxs("div", { className: "input-group", children: [_jsx("input", { type: isPassword ? (showPassword ? "text" : "password") : type, placeholder: label, ...register(name), className: `form-control ${errors[name] ? "is-invalid" : ""}` }), isPassword && (_jsx("span", { className: "input-group-text bg-white", style: { cursor: "pointer" }, onClick: () => setShowPassword((prev) => !prev), children: showPassword ? _jsx(FaEye, { size: 18 }) : _jsx(FaEyeSlash, { size: 18 }) }))] }), errors[name] && (_jsx("div", { className: "invalid-feedback d-block", children: errors[name]?.message }))] }));
|
|
143
145
|
};
|
|
144
|
-
return (_jsx("div", { className: "d-flex justify-content-center align-items-center vh-100 bg-light", children: _jsx("div", { className: "card shadow-sm p-4 p-md-5 w-100", style: { maxWidth: "420px" }, children: _jsxs("form", { onSubmit: handleSubmit(onSubmit), children: [_jsx("div", { className: "d-flex justify-content-center", children: _jsx("img", { className: "w-75 mx-auto mb-4", src:
|
|
146
|
+
return (_jsx("div", { className: "d-flex justify-content-center align-items-center vh-100 bg-light", children: _jsx("div", { className: "card shadow-sm p-4 p-md-5 w-100", style: { maxWidth: "420px" }, children: _jsxs("form", { onSubmit: handleSubmit(onSubmit), children: [_jsx("div", { className: "d-flex justify-content-center", children: _jsx("img", { className: "w-75 mx-auto mb-4", src: logo }) }), _jsxs("h4", { className: "text-center mb-4 fw-bold", children: [authMode === "signin" && "Sign in to your account", authMode === "register" && "Create a new account", authMode === "confirm" && "Verify your email", authMode === "forgot" && "Forgot Password?", authMode === "reset" && "Reset Password", authMode === "forceReset" && "Set New Password"] }), authMode === "signin" && (_jsxs(_Fragment, { children: [renderInput("Username", "text", "username"), renderInput("Password", "password", "password"), _jsx("button", { type: "submit", className: "btn btn-primary w-100 mb-2", children: "Sign In" }), _jsxs("div", { className: "d-flex justify-content-between", children: [(settingsByPkAndSk && settingsByPkAndSk?.value === HIDE_SIGN_UP_IS_NO) &&
|
|
147
|
+
_jsx("button", { type: "button", className: "btn btn-link p-0", onClick: () => setAuthMode("register"), children: "Create Account" }), _jsx("button", { type: "button", className: "btn btn-link p-0", onClick: () => setAuthMode("forgot"), children: "Forgot Password?" })] })] })), authMode === "register" && (_jsxs(_Fragment, { children: [renderInput("Username", "text", "username"), renderInput("Email", "email", "email"), renderInput("Password", "password", "password"), renderInput("Confirm Password", "password", "confirmPassword"), _jsx("button", { type: "submit", className: "btn btn-success w-100 mb-2", children: "Register" }), _jsx("button", { type: "button", className: "btn btn-link w-100", onClick: () => setAuthMode("signin"), children: "Back to Sign In" })] })), authMode === "confirm" && (_jsxs(_Fragment, { children: [renderInput("Verification Code", "text", "confirmationCode"), _jsx("button", { type: "submit", className: "btn btn-primary w-100 mb-2", children: "Confirm" }), _jsx("button", { type: "button", className: "btn btn-link w-100", onClick: () => setAuthMode("signin"), children: "Back to Sign In" })] })), authMode === "forgot" && (_jsxs(_Fragment, { children: [renderInput("Username", "text", "username"), _jsx("button", { type: "submit", className: "btn btn-warning w-100 mb-2", children: "Send Reset Code" }), _jsx("button", { type: "button", className: "btn btn-link w-100", onClick: () => setAuthMode("signin"), children: "Back to Sign In" })] })), authMode === "reset" && (_jsxs(_Fragment, { children: [renderInput("Verification Code", "text", "confirmationCode"), renderInput("New Password", "password", "password"), renderInput("Confirm New Password", "password", "confirmPassword"), _jsx("button", { type: "submit", className: "btn btn-success w-100 mb-2", children: "Reset Password" }), _jsx("button", { type: "button", className: "btn btn-link w-100", onClick: () => setAuthMode("signin"), children: "Back to Sign In" })] })), authMode === "forceReset" && (_jsxs(_Fragment, { children: [renderInput("New Password", "password", "password"), renderInput("Confirm New Password", "password", "confirmPassword"), _jsx("button", { type: "submit", className: "btn btn-success w-100 mb-2", children: "Update Password" }), _jsx("button", { type: "button", className: "btn btn-link w-100", onClick: () => setAuthMode("signin"), children: "Back to Sign In" })] }))] }) }) }));
|
|
145
148
|
};
|
|
146
149
|
export default LoginForm;
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
-
import {
|
|
2
|
+
import { useContext, useMemo, useState } from "react";
|
|
3
3
|
import MappingForm from "../MappingForm/MappingForm";
|
|
4
4
|
import FormModal from "../../common/Modal/Modal";
|
|
5
5
|
import ListTable from "../../common/ListTable/ListTable";
|
|
6
6
|
import { toast } from "react-toastify";
|
|
7
7
|
import { MappingTypes } from "../../../domain/type/MappingTypes";
|
|
8
|
-
import { getCompoMappingByRoleIdAndCompoIdFun, useCreateMappingMutation, useListComponentRoleMappings,
|
|
8
|
+
import { getCompoMappingByRoleIdAndCompoIdFun, useCreateMappingMutation, useListComponentRoleMappings, useUpdateMappingMutation, } from "../../../api/mapping-api";
|
|
9
9
|
import { EntityTypes } from "../../../domain/type/EntityTypes";
|
|
10
10
|
import { Status } from "../../../domain/type/StatusEnum";
|
|
11
11
|
import { SyzyDate } from "../../../util/SyzyDate";
|
|
12
12
|
import { DATE_FORMAT_ISO_YYYY_MM_DD_HH_MM_SS } from "../../../util/dateUtils";
|
|
13
|
+
import AppContext from "../../../store/AppContext";
|
|
13
14
|
import { logger } from "../../../util/Logger";
|
|
14
15
|
import { componentMap } from "../../../App";
|
|
15
16
|
import { roles } from "../RoleMapping/MappingFormUserRole";
|
|
@@ -18,7 +19,8 @@ import ListHeader from "../../common/ListTable/ListHeader";
|
|
|
18
19
|
import { ToastContainer } from "react-toastify";
|
|
19
20
|
/* ---------------- Component Role Mapping ---------------- */
|
|
20
21
|
const ComponentRoleMappingPage = () => {
|
|
21
|
-
const
|
|
22
|
+
const { user } = useContext(AppContext) || {};
|
|
23
|
+
const loggedInUserName = user?.userName;
|
|
22
24
|
const [showModal, setShowModal] = useState(false);
|
|
23
25
|
const [editingRow, setEditingRow] = useState();
|
|
24
26
|
const currentISODate = new SyzyDate().toDateFormatString(DATE_FORMAT_ISO_YYYY_MM_DD_HH_MM_SS);
|
|
@@ -26,12 +28,6 @@ const ComponentRoleMappingPage = () => {
|
|
|
26
28
|
const createMappingMutation = useCreateMappingMutation();
|
|
27
29
|
const updateMappingMutation = useUpdateMappingMutation();
|
|
28
30
|
const tableLoading = isLoading || createMappingMutation.isPending || updateMappingMutation.isPending;
|
|
29
|
-
const { data: profiles } = useListProfiles();
|
|
30
|
-
useEffect(() => {
|
|
31
|
-
if (profiles) {
|
|
32
|
-
setUsers(profiles.map((p) => ({ id: p.sk, name: p.name })));
|
|
33
|
-
}
|
|
34
|
-
}, [profiles]);
|
|
35
31
|
/* ---------------- Component Options ---------------- */
|
|
36
32
|
const components = useMemo(() => Object.keys(componentMap).map((key, index) => ({
|
|
37
33
|
id: `Component#${String(index + 1).padStart(2, "0")}`,
|
|
@@ -50,10 +46,9 @@ const ComponentRoleMappingPage = () => {
|
|
|
50
46
|
const handleSubmit = async (mappings) => {
|
|
51
47
|
try {
|
|
52
48
|
for (const map of mappings) {
|
|
53
|
-
const user = users.find(u => u.id === map.sourceId);
|
|
54
49
|
const role = roles.find(r => r.id === map.targetId);
|
|
55
50
|
const component = components.find(c => c.id === map.sourceId);
|
|
56
|
-
if (!
|
|
51
|
+
if (!role || !component || !loggedInUserName)
|
|
57
52
|
continue;
|
|
58
53
|
const payload = {
|
|
59
54
|
pk: role.id,
|
|
@@ -67,7 +62,7 @@ const ComponentRoleMappingPage = () => {
|
|
|
67
62
|
componentTitle: component.name,
|
|
68
63
|
status: map.status,
|
|
69
64
|
createdDt: editingRow?.createdDt || currentISODate,
|
|
70
|
-
createdBy:
|
|
65
|
+
createdBy: loggedInUserName,
|
|
71
66
|
disabledDt: map.status === Status.Inactive ? currentISODate : "",
|
|
72
67
|
};
|
|
73
68
|
const existing = await getCompoMappingByRoleIdAndCompoIdFun(payload.pk, payload.sk);
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { useContext, useEffect, useState } from "react";
|
|
3
|
+
import { transformdToPrefixDescription, useGetSettingsByPk, useUpdateSettingsMutation } from "../api/settings-api";
|
|
4
|
+
import { Button, Card, Col, Container, Form, Modal, Row } from "react-bootstrap";
|
|
5
|
+
import { toast } from "react-toastify";
|
|
6
|
+
import { BsPencilSquare, BsCheckCircle, BsXCircle, BsInfoCircle } from "react-icons/bs";
|
|
7
|
+
import './SettingsPage.css';
|
|
8
|
+
import { ALL, BOOKING_RECEIPT_PREFIX_FORMAT, BOOKING_RECEIPT_RESETTING_PERIOD, BOOKING_RECEIPT_SEQUENCE_PADDING, BOOKING_RECEIPT_SERIES_NUMBER, HIDE_SIGN_UP, INVOICE_PREFIX_FORMAT, INVOICE_RESETTING_PERIOD, INVOICE_SEQUENCE_PADDING, INVOICE_SERIES_NUMBER, NEVER, PURCHASE_ORDER_PREFIX_FORMAT, PURCHASE_ORDER_RESETTING_PERIOD, PURCHASE_ORDER_SEQUENCE_PADDING, RESERVATION_PREFIX_FORMAT, RESERVATION_RESETTING_PERIOD, RESERVATION_SEQUENCE_PADDING } from "../../static/constants";
|
|
9
|
+
import Select from "react-select";
|
|
10
|
+
import { ResettingPeriodOptions } from "../../domain/type/ResettingPeriodOptions";
|
|
11
|
+
import { initPrefixDescription } from "../../domain/model/PrefixDescriptionDto";
|
|
12
|
+
import { resettingOptions, validateFirstOccurance, validateFullWrapper } from "../../util/prefixAndResettingValidation";
|
|
13
|
+
import { logger } from "../../util/Logger";
|
|
14
|
+
import AppContext from "../../store/AppContext";
|
|
15
|
+
import { sighUpOptions } from "../../domain/type/signUpOptions";
|
|
16
|
+
import { Roles } from "../../domain/type/RolesEnum";
|
|
17
|
+
const SettingsPage = () => {
|
|
18
|
+
const { user } = useContext(AppContext) ?? { user: undefined };
|
|
19
|
+
const rawBranch = user?.branchId ?? "";
|
|
20
|
+
const parts = rawBranch.split("#");
|
|
21
|
+
const branchId = parts[1];
|
|
22
|
+
const userRoles = user?.roles ?? [];
|
|
23
|
+
const { settingsByPK } = useGetSettingsByPk(branchId);
|
|
24
|
+
const updateSettingsMutation = useUpdateSettingsMutation();
|
|
25
|
+
const [editStates, setEditStates] = useState({});
|
|
26
|
+
const [activeEditKey, setActiveEditKey] = useState(null);
|
|
27
|
+
const defaultInvResettingPeriodOption = ResettingPeriodOptions.find(option => option.value === "");
|
|
28
|
+
const [selectedInvResettingPeriod, setSelectedInvResettingPeriod] = useState(defaultInvResettingPeriodOption);
|
|
29
|
+
const defaultPurchaseOrderResetPeriodOption = ResettingPeriodOptions.find(option => option.value === "");
|
|
30
|
+
const [selectedPurchaseOrderResettingPeriod, setSelectedPurchaseOrdResettingPeriod] = useState(defaultPurchaseOrderResetPeriodOption);
|
|
31
|
+
const defaultReservationResetPeriodOption = ResettingPeriodOptions.find(option => option.value === "");
|
|
32
|
+
const [selectedReservationResettingPeriod, setSelectedReservationResettingPeriod] = useState(defaultReservationResetPeriodOption);
|
|
33
|
+
const defaultBookingReceiptResetPeriodOption = ResettingPeriodOptions.find(option => option.value === "");
|
|
34
|
+
const [selectedBookingReceiptResettingPeriod, setSelectedBookingReceiptResettingPeriod] = useState(defaultBookingReceiptResetPeriodOption);
|
|
35
|
+
const [showPrefixInfo, setShowPrefixInfo] = useState(false);
|
|
36
|
+
const [prefixDescription, setPrefixDescription] = useState(initPrefixDescription);
|
|
37
|
+
const defaultSignUpOption = sighUpOptions.find(option => option.value === "");
|
|
38
|
+
const [selectedSignUpOption, setSelectedSighUpOPtion] = useState(defaultSignUpOption);
|
|
39
|
+
useEffect(() => {
|
|
40
|
+
if (settingsByPK && settingsByPK.length > 0) {
|
|
41
|
+
const invResetPeriod = settingsByPK.find((setting) => setting.sk === INVOICE_RESETTING_PERIOD);
|
|
42
|
+
const purchaseOrdResetPeriod = settingsByPK.find((setting) => setting.sk === PURCHASE_ORDER_RESETTING_PERIOD);
|
|
43
|
+
const reservationResetPeriod = settingsByPK.find((setting) => setting.sk === RESERVATION_RESETTING_PERIOD);
|
|
44
|
+
const bookingReceiptResetPeriod = settingsByPK.find((setting) => setting.sk === BOOKING_RECEIPT_RESETTING_PERIOD);
|
|
45
|
+
const hideSignUp = settingsByPK.find((setting) => setting.sk === HIDE_SIGN_UP);
|
|
46
|
+
setSelectedInvResettingPeriod({ label: invResetPeriod?.value ?? '', value: invResetPeriod?.sk ?? '' });
|
|
47
|
+
setSelectedPurchaseOrdResettingPeriod({ label: purchaseOrdResetPeriod?.value ?? '', value: purchaseOrdResetPeriod?.sk ?? '' });
|
|
48
|
+
setSelectedReservationResettingPeriod({ label: reservationResetPeriod?.value ?? '', value: reservationResetPeriod?.sk ?? '' });
|
|
49
|
+
setSelectedBookingReceiptResettingPeriod({ label: bookingReceiptResetPeriod?.value ?? '', value: bookingReceiptResetPeriod?.sk ?? '' });
|
|
50
|
+
setSelectedSighUpOPtion({ label: hideSignUp?.value ?? '', value: hideSignUp?.sk ?? '' });
|
|
51
|
+
}
|
|
52
|
+
}, [settingsByPK]);
|
|
53
|
+
const handleEdit = (sk, currentValue) => {
|
|
54
|
+
setActiveEditKey(sk);
|
|
55
|
+
setEditStates((prev) => ({
|
|
56
|
+
...prev,
|
|
57
|
+
[sk]: { isEditing: true, value: currentValue }
|
|
58
|
+
}));
|
|
59
|
+
};
|
|
60
|
+
const handleCancel = (sk) => {
|
|
61
|
+
setActiveEditKey(null);
|
|
62
|
+
setEditStates((prev) => ({
|
|
63
|
+
...prev,
|
|
64
|
+
[sk]: { isEditing: false, value: prev[sk]?.value || "" },
|
|
65
|
+
}));
|
|
66
|
+
};
|
|
67
|
+
const handleChange = (sk, newValue) => {
|
|
68
|
+
setEditStates((prev) => ({ ...prev, [sk]: { ...prev[sk], value: newValue }, }));
|
|
69
|
+
};
|
|
70
|
+
const handleResettingPeriodChange = (sk, selectedOption) => {
|
|
71
|
+
if (selectedOption) {
|
|
72
|
+
const selectedVal = selectedOption.value;
|
|
73
|
+
setEditStates((prev) => ({ ...prev, [sk]: { ...prev[sk], value: selectedVal }, }));
|
|
74
|
+
if (sk === INVOICE_RESETTING_PERIOD) {
|
|
75
|
+
setSelectedInvResettingPeriod({ label: selectedVal, value: sk ?? '' });
|
|
76
|
+
}
|
|
77
|
+
else if (sk === PURCHASE_ORDER_RESETTING_PERIOD) {
|
|
78
|
+
setSelectedPurchaseOrdResettingPeriod({ label: selectedVal, value: sk ?? '' });
|
|
79
|
+
}
|
|
80
|
+
else if (sk === RESERVATION_RESETTING_PERIOD) {
|
|
81
|
+
setSelectedReservationResettingPeriod({ label: selectedVal, value: sk ?? '' });
|
|
82
|
+
}
|
|
83
|
+
else if (sk === BOOKING_RECEIPT_RESETTING_PERIOD) {
|
|
84
|
+
setSelectedBookingReceiptResettingPeriod({ label: selectedVal, value: sk ?? '' });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const upsertSettingsMutationFn = (settingsData) => {
|
|
89
|
+
try {
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
updateSettingsMutation.mutate(settingsData, {
|
|
92
|
+
onSuccess: (_res) => {
|
|
93
|
+
toast.success("Settings update successfully!");
|
|
94
|
+
resolve();
|
|
95
|
+
},
|
|
96
|
+
onError: (err) => {
|
|
97
|
+
toast.error("Error while request the Product");
|
|
98
|
+
reject(err);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
logger.error("error at product request updation", err);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const validatePrefixResetting = (prefixSk, resetSk) => {
|
|
108
|
+
const prefix = editStates[prefixSk]?.value ||
|
|
109
|
+
settingsByPK?.find(s => s.sk === prefixSk)?.value || "";
|
|
110
|
+
const resettingPeriod = editStates[resetSk]?.value ||
|
|
111
|
+
settingsByPK?.find(s => s.sk === resetSk)?.value || "";
|
|
112
|
+
const allowedPrefix = /^[a-zA-Z]+$/.test(prefix);
|
|
113
|
+
if (allowedPrefix) {
|
|
114
|
+
return true; // bypass resetting validation for custom prefixes
|
|
115
|
+
}
|
|
116
|
+
const allowedPeriods = getAllowedResettingPeriods(prefix).map(opt => opt.value);
|
|
117
|
+
if (!allowedPeriods.includes(resettingPeriod)) {
|
|
118
|
+
toast.info("Resetting period is not suitable for prefix format. Please select other resetting options before updating prefix.");
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
return true;
|
|
122
|
+
};
|
|
123
|
+
const handleUpdate = (settingData) => {
|
|
124
|
+
const newValue = editStates[settingData.sk]?.value;
|
|
125
|
+
// ✅ Series number validation (must be greater than existing)
|
|
126
|
+
if (settingData.sk === INVOICE_SERIES_NUMBER ||
|
|
127
|
+
settingData.sk === BOOKING_RECEIPT_SERIES_NUMBER) {
|
|
128
|
+
const existingValue = Number(settingData.value);
|
|
129
|
+
const enteredValue = Number(newValue);
|
|
130
|
+
if (isNaN(enteredValue)) {
|
|
131
|
+
toast.error("Please enter a valid number.");
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (enteredValue <= existingValue) {
|
|
135
|
+
toast.error(`New series number must be greater than existing value (${existingValue}).`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const allowedPrefix = (settingData.sk === INVOICE_PREFIX_FORMAT || settingData.sk === BOOKING_RECEIPT_PREFIX_FORMAT) && /^[a-zA-Z]+$/.test(newValue);
|
|
140
|
+
// check allowed predefined constant usage -----
|
|
141
|
+
if (settingData.sk === INVOICE_PREFIX_FORMAT || settingData.sk === PURCHASE_ORDER_PREFIX_FORMAT || settingData.sk === RESERVATION_PREFIX_FORMAT || settingData.sk === BOOKING_RECEIPT_PREFIX_FORMAT) {
|
|
142
|
+
const invalidWrapper = validateFullWrapper(newValue);
|
|
143
|
+
if (invalidWrapper && !allowedPrefix) {
|
|
144
|
+
toast.info("Predefined constants only allowed. Please check the prefix format.");
|
|
145
|
+
return; // stop update
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
// first occurance check-------------
|
|
149
|
+
if (settingData.sk === INVOICE_PREFIX_FORMAT || settingData.sk === PURCHASE_ORDER_PREFIX_FORMAT || settingData.sk === RESERVATION_PREFIX_FORMAT || settingData.sk === BOOKING_RECEIPT_PREFIX_FORMAT) {
|
|
150
|
+
const { firstWrapper, validTokens } = validateFirstOccurance(newValue);
|
|
151
|
+
if (!allowedPrefix) {
|
|
152
|
+
if (!firstWrapper || !validTokens.includes(firstWrapper)) {
|
|
153
|
+
toast.info("Predefined constant must start with {FY}, {fy}, {Y}, {y}, {M}, or {D}.");
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// check prefix and resetting combination ----------
|
|
159
|
+
if (settingData.sk === INVOICE_PREFIX_FORMAT || settingData.sk === INVOICE_RESETTING_PERIOD) {
|
|
160
|
+
if (!validatePrefixResetting(INVOICE_PREFIX_FORMAT, INVOICE_RESETTING_PERIOD))
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (settingData.sk === PURCHASE_ORDER_PREFIX_FORMAT || settingData.sk === PURCHASE_ORDER_RESETTING_PERIOD) {
|
|
164
|
+
if (!validatePrefixResetting(PURCHASE_ORDER_PREFIX_FORMAT, PURCHASE_ORDER_RESETTING_PERIOD))
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (settingData.sk === RESERVATION_PREFIX_FORMAT || settingData.sk === RESERVATION_RESETTING_PERIOD) {
|
|
168
|
+
if (!validatePrefixResetting(RESERVATION_PREFIX_FORMAT, RESERVATION_RESETTING_PERIOD))
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (settingData.sk === BOOKING_RECEIPT_PREFIX_FORMAT || settingData.sk === BOOKING_RECEIPT_RESETTING_PERIOD) {
|
|
172
|
+
if (!validatePrefixResetting(BOOKING_RECEIPT_PREFIX_FORMAT, BOOKING_RECEIPT_RESETTING_PERIOD))
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
setActiveEditKey(null);
|
|
176
|
+
setEditStates((prev) => ({
|
|
177
|
+
...prev,
|
|
178
|
+
[settingData.sk]: { isEditing: false, value: newValue || "" }
|
|
179
|
+
}));
|
|
180
|
+
settingData.value = newValue;
|
|
181
|
+
// don't change pk for sign up option if super admin
|
|
182
|
+
settingData.pk = (settingData.pk === ALL && settingData.sk === HIDE_SIGN_UP && userRoles.includes(Roles.SuperAdmin)) ? settingData.pk : branchId;
|
|
183
|
+
upsertSettingsMutationFn(settingData);
|
|
184
|
+
};
|
|
185
|
+
const getAllowedResettingPeriods = (prefix) => {
|
|
186
|
+
if (!prefix) {
|
|
187
|
+
return ResettingPeriodOptions.filter(opt => opt.value === NEVER);
|
|
188
|
+
}
|
|
189
|
+
const firstMatch = resettingOptions(prefix);
|
|
190
|
+
if (firstMatch) {
|
|
191
|
+
return ResettingPeriodOptions.filter(opt => firstMatch.periods.includes(opt.value));
|
|
192
|
+
}
|
|
193
|
+
// NONE prefix → only NEVER
|
|
194
|
+
return ResettingPeriodOptions.filter(opt => opt.value === NEVER);
|
|
195
|
+
};
|
|
196
|
+
const handleSignUpOptionChange = (sk, selectedOption) => {
|
|
197
|
+
if (selectedOption) {
|
|
198
|
+
const selectedVal = selectedOption.value;
|
|
199
|
+
setEditStates((prev) => ({ ...prev, [sk]: { ...prev[sk], value: selectedVal }, }));
|
|
200
|
+
setSelectedSighUpOPtion({ label: selectedVal, value: sk ?? '' });
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
return (_jsxs(Container, { className: "mt-4", children: [settingsByPK && settingsByPK.length > 0 && (_jsxs(Card, { className: "shadow-lg settings-card", children: [_jsx(Card.Header, { className: "fw-bold", children: "Settings" }), _jsx(Card.Body, { children: settingsByPK.map((setting) => {
|
|
204
|
+
const editState = editStates[setting.sk] || { isEditing: false, value: setting.value };
|
|
205
|
+
const isActive = activeEditKey === setting.sk;
|
|
206
|
+
return (_jsxs(Row, { className: "align-items-center mb-3", children: [_jsxs(Col, { xs: 3, sm: 3, md: 3, lg: 5, xl: 5, className: "fw-bold settings-key-col", children: [setting.pk === ALL && setting.sk === HIDE_SIGN_UP && !userRoles.includes(Roles.SuperAdmin) ? "" : setting.sk, (setting.sk === INVOICE_PREFIX_FORMAT || setting.sk === PURCHASE_ORDER_PREFIX_FORMAT || setting.sk === RESERVATION_PREFIX_FORMAT || setting.sk === BOOKING_RECEIPT_PREFIX_FORMAT) && (_jsx(Button, { size: "sm", variant: "link", className: "ms-2 p-0 text-info mb-1", onClick: () => {
|
|
207
|
+
setShowPrefixInfo(true);
|
|
208
|
+
setPrefixDescription(transformdToPrefixDescription(setting.description));
|
|
209
|
+
}, children: _jsx(BsInfoCircle, { className: "info-icon" }) }))] }), _jsx(Col, { xs: 3, sm: 3, md: 5, lg: 5, xl: 5, className: "settings-value-col", children: !isActive ? (_jsx("span", { children: setting.pk === ALL && setting.sk === HIDE_SIGN_UP && !userRoles.includes(Roles.SuperAdmin) ? "" : setting.value })) : (_jsxs(_Fragment, { children: [(setting.sk === INVOICE_RESETTING_PERIOD || setting.sk === PURCHASE_ORDER_RESETTING_PERIOD || setting.sk === RESERVATION_RESETTING_PERIOD || setting.sk === BOOKING_RECEIPT_RESETTING_PERIOD) ?
|
|
210
|
+
_jsx(Select, { options: getAllowedResettingPeriods(setting.sk === INVOICE_RESETTING_PERIOD
|
|
211
|
+
? settingsByPK.find(s => s.sk === INVOICE_PREFIX_FORMAT)?.value ?? ""
|
|
212
|
+
: setting.sk === PURCHASE_ORDER_RESETTING_PERIOD
|
|
213
|
+
? settingsByPK.find(s => s.sk === PURCHASE_ORDER_PREFIX_FORMAT)?.value ?? ""
|
|
214
|
+
: setting.sk === RESERVATION_RESETTING_PERIOD
|
|
215
|
+
? settingsByPK.find(s => s.sk === RESERVATION_PREFIX_FORMAT)?.value ?? ""
|
|
216
|
+
: settingsByPK.find(s => s.sk === BOOKING_RECEIPT_PREFIX_FORMAT)?.value ?? ""), value: setting.sk === INVOICE_RESETTING_PERIOD
|
|
217
|
+
? selectedInvResettingPeriod
|
|
218
|
+
: setting.sk === PURCHASE_ORDER_RESETTING_PERIOD
|
|
219
|
+
? selectedPurchaseOrderResettingPeriod
|
|
220
|
+
: setting.sk === RESERVATION_RESETTING_PERIOD
|
|
221
|
+
? selectedReservationResettingPeriod
|
|
222
|
+
: selectedBookingReceiptResettingPeriod, onChange: (selectedOption) => selectedOption && handleResettingPeriodChange(setting.sk, selectedOption), placeholder: "Select resetting period", className: "resetting-period-select", maxMenuHeight: 200 }) : (setting.pk === ALL && setting.sk === HIDE_SIGN_UP && userRoles.includes(Roles.SuperAdmin)) ?
|
|
223
|
+
_jsx(Select, { options: sighUpOptions, value: selectedSignUpOption, onChange: (selectedOption) => selectedOption && handleSignUpOptionChange(setting.sk, selectedOption), placeholder: "Select Sign up option", className: "resetting-period-select", maxMenuHeight: 200 }) :
|
|
224
|
+
(setting.sk === INVOICE_PREFIX_FORMAT ||
|
|
225
|
+
setting.sk === PURCHASE_ORDER_PREFIX_FORMAT ||
|
|
226
|
+
setting.sk === RESERVATION_PREFIX_FORMAT ||
|
|
227
|
+
setting.sk === BOOKING_RECEIPT_PREFIX_FORMAT ||
|
|
228
|
+
setting.sk === INVOICE_SEQUENCE_PADDING ||
|
|
229
|
+
setting.sk === PURCHASE_ORDER_SEQUENCE_PADDING ||
|
|
230
|
+
setting.sk === RESERVATION_SEQUENCE_PADDING ||
|
|
231
|
+
setting.sk === BOOKING_RECEIPT_SEQUENCE_PADDING ||
|
|
232
|
+
setting.sk === INVOICE_SERIES_NUMBER ||
|
|
233
|
+
setting.sk === BOOKING_RECEIPT_SERIES_NUMBER) ?
|
|
234
|
+
_jsx(Form.Control, { type: (setting.sk === INVOICE_SEQUENCE_PADDING || setting.sk === PURCHASE_ORDER_SEQUENCE_PADDING || setting.sk === RESERVATION_SEQUENCE_PADDING || setting.sk === BOOKING_RECEIPT_SEQUENCE_PADDING) ? 'number' : 'text', value: editState.value, onChange: (e) => handleChange(setting.sk, e.target.value), className: "settings-value-form-control" })
|
|
235
|
+
: null, ((setting.sk === INVOICE_SEQUENCE_PADDING) || (setting.sk === PURCHASE_ORDER_SEQUENCE_PADDING) || (setting.sk === RESERVATION_SEQUENCE_PADDING) || (setting.sk === BOOKING_RECEIPT_SEQUENCE_PADDING)) &&
|
|
236
|
+
_jsx("label", { className: "seq-pad-info text-primary", children: setting.description })] })) }), setting.pk === ALL && setting.sk === HIDE_SIGN_UP && !userRoles.includes(Roles.SuperAdmin) ? null :
|
|
237
|
+
_jsx(Col, { xs: 3, sm: 3, md: 4, lg: 5, xl: 5, className: "text-end settings-btns", children: !isActive ? (_jsx(Button, { size: "sm", variant: "outline-primary", className: "edit-btn", onClick: () => handleEdit(setting.sk, setting.value), children: _jsx(BsPencilSquare, {}) })) : (_jsxs(_Fragment, { children: [_jsx(Button, { size: "sm", variant: "success", className: "me-2 update-btn", onClick: () => handleUpdate(setting), children: _jsx(BsCheckCircle, {}) }), _jsx(Button, { size: "sm", variant: "secondary", className: "cancel-btn", onClick: () => handleCancel(setting.sk), children: _jsx(BsXCircle, {}) })] })) })] }, setting.sk));
|
|
238
|
+
}) })] })), _jsxs(Modal, { show: showPrefixInfo, onHide: () => setShowPrefixInfo(false), size: "lg", centered: true, children: [_jsx(Modal.Header, { closeButton: true, children: _jsx(Modal.Title, { children: "Prefix Format Info" }) }), _jsxs(Modal.Body, { children: [_jsx("p", { className: "fw-bold", children: prefixDescription.message }), prefixDescription.constants.map((constant, index) => (_jsxs("p", { children: [constant.constant, " - ", constant.description] }, index))), _jsx("b", { className: "text-success", children: "Example:" }), _jsxs("p", { children: [_jsx("strong", { children: "Prefix:" }), " ", prefixDescription.example.prefixFormat] }), _jsxs("p", { children: [_jsx("strong", { children: "Result:" }), " ", prefixDescription.example.outputValue] })] }), _jsx(Modal.Footer, { children: _jsx(Button, { variant: "secondary", onClick: () => setShowPrefixInfo(false), children: "Close" }) })] })] }));
|
|
239
|
+
};
|
|
240
|
+
export default SettingsPage;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { SettingsDto } from "../../domain/model/SettingsDto";
|
|
2
|
+
import { UndefinedString } from "../../domain/type/Nullable";
|
|
3
|
+
import { PrefixDescription } from "../../domain/model/PrefixDescriptionDto";
|
|
4
|
+
export declare const GET_SETTINGS_BY_PK: string;
|
|
5
|
+
export declare const GET_SETTINGS_BY_PK_AND_SK: string;
|
|
6
|
+
export declare const listSettings = "query listSettings(\n $pk: ID\n $sk: ModelStringKeyConditionInput\n $filter: ModelSettingsFilterInput\n) {\n listSettings(pk: $pk, sk: $sk, filter: $filter) {\n pk\n sk\n value\n description\n createdDt\n __typename\n }\n}";
|
|
7
|
+
export declare const updateSettings = "mutation updateSettings($input: SettingsInput!) {\n updateSettings(input: $input) {\n pk\n sk\n value\n description\n createdDt\n __typename\n }\n}";
|
|
8
|
+
export declare const transformtoSettingsDto: (interviewProspectData: any) => SettingsDto;
|
|
9
|
+
export declare const transformdToPrefixDescription: (description: string) => PrefixDescription;
|
|
10
|
+
export declare const getSettingsByPkFun: (pk: UndefinedString) => Promise<SettingsDto[]>;
|
|
11
|
+
export declare const useGetSettingsByPk: (pk: string) => {
|
|
12
|
+
settingsByPK: SettingsDto[] | undefined;
|
|
13
|
+
settingsByPKError: Error | null;
|
|
14
|
+
settingsByPKLoading: boolean;
|
|
15
|
+
settingsByPKFetching: boolean;
|
|
16
|
+
settingsByPKSuccess: boolean;
|
|
17
|
+
};
|
|
18
|
+
export declare const getSettingsByPkAndSKFun: (pk: UndefinedString, sk: UndefinedString) => Promise<SettingsDto>;
|
|
19
|
+
export declare const useGetSettingsByPkAndSk: (pk: string, sk: string) => {
|
|
20
|
+
settingsByPkAndSk: SettingsDto | undefined;
|
|
21
|
+
settingsByPkAndSkError: Error | null;
|
|
22
|
+
settingsByPkAndSkLoading: boolean;
|
|
23
|
+
settingsByPkAndSkFetching: boolean;
|
|
24
|
+
settingsByPkAndSkSuccess: boolean;
|
|
25
|
+
};
|
|
26
|
+
export declare const useUpdateSettingsMutation: () => import("@tanstack/react-query").UseMutationResult<import("@aws-amplify/api-graphql").GraphQLResult<any> | import("@aws-amplify/api-graphql").GraphqlSubscriptionResult<any>, Error, SettingsDto, unknown>;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
2
|
+
import { EnvConfig } from "../../config/EnvConfig";
|
|
3
|
+
import { initSettings } from "../../domain/model/SettingsDto";
|
|
4
|
+
import { Client } from "../../services/Client.Service";
|
|
5
|
+
import { transformToData } from "../../util/transformToData";
|
|
6
|
+
import { logger } from "../../util/Logger";
|
|
7
|
+
import { ALL } from "../../static/constants";
|
|
8
|
+
export const GET_SETTINGS_BY_PK = "settingsbypk";
|
|
9
|
+
export const GET_SETTINGS_BY_PK_AND_SK = "settingsbypkandsk";
|
|
10
|
+
const endpoint = EnvConfig.appHostAPi;
|
|
11
|
+
export const listSettings = `query listSettings(
|
|
12
|
+
$pk: ID
|
|
13
|
+
$sk: ModelStringKeyConditionInput
|
|
14
|
+
$filter: ModelSettingsFilterInput
|
|
15
|
+
) {
|
|
16
|
+
listSettings(pk: $pk, sk: $sk, filter: $filter) {
|
|
17
|
+
pk
|
|
18
|
+
sk
|
|
19
|
+
value
|
|
20
|
+
description
|
|
21
|
+
createdDt
|
|
22
|
+
__typename
|
|
23
|
+
}
|
|
24
|
+
}`;
|
|
25
|
+
export const updateSettings = `mutation updateSettings($input: SettingsInput!) {
|
|
26
|
+
updateSettings(input: $input) {
|
|
27
|
+
pk
|
|
28
|
+
sk
|
|
29
|
+
value
|
|
30
|
+
description
|
|
31
|
+
createdDt
|
|
32
|
+
__typename
|
|
33
|
+
}
|
|
34
|
+
}`;
|
|
35
|
+
export const transformtoSettingsDto = (interviewProspectData) => transformToData(interviewProspectData);
|
|
36
|
+
export const transformdToPrefixDescription = (description) => {
|
|
37
|
+
return JSON.parse(description);
|
|
38
|
+
};
|
|
39
|
+
export const getSettingsByPkFun = async (pk) => {
|
|
40
|
+
try {
|
|
41
|
+
const client = await Client.getCustomGraphqlClient(endpoint);
|
|
42
|
+
const variables = {
|
|
43
|
+
filter: {
|
|
44
|
+
or: [
|
|
45
|
+
{ pk: { eq: pk } },
|
|
46
|
+
{ pk: { eq: ALL } }
|
|
47
|
+
]
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const response = await client.request(listSettings, variables);
|
|
51
|
+
const settingsData = response.listSettings;
|
|
52
|
+
return (settingsData && settingsData.length > 0) ? settingsData.map((eventSchedule) => transformtoSettingsDto(eventSchedule)) : [];
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
export const useGetSettingsByPk = (pk) => {
|
|
59
|
+
const { data, isLoading, error, isFetching, isSuccess } = useQuery({
|
|
60
|
+
queryKey: [GET_SETTINGS_BY_PK, pk],
|
|
61
|
+
queryFn: () => getSettingsByPkFun(pk),
|
|
62
|
+
placeholderData: keepPreviousData,
|
|
63
|
+
staleTime: 1000 * 5 * 60,
|
|
64
|
+
enabled: pk !== "" && pk !== undefined,
|
|
65
|
+
});
|
|
66
|
+
return {
|
|
67
|
+
settingsByPK: data,
|
|
68
|
+
settingsByPKError: error,
|
|
69
|
+
settingsByPKLoading: isLoading,
|
|
70
|
+
settingsByPKFetching: isFetching,
|
|
71
|
+
settingsByPKSuccess: isSuccess,
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
export const getSettingsByPkAndSKFun = async (pk, sk) => {
|
|
75
|
+
try {
|
|
76
|
+
const client = await Client.getCustomGraphqlClient(endpoint);
|
|
77
|
+
const variables = {
|
|
78
|
+
pk: pk,
|
|
79
|
+
sk: {
|
|
80
|
+
eq: sk
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const response = await client.request(listSettings, variables);
|
|
84
|
+
const settingsData = response.listSettings;
|
|
85
|
+
return (settingsData && settingsData.length > 0) ? transformtoSettingsDto(settingsData[0]) : initSettings;
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
return initSettings;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
export const useGetSettingsByPkAndSk = (pk, sk) => {
|
|
92
|
+
const { data, isLoading, error, isFetching, isSuccess } = useQuery({
|
|
93
|
+
queryKey: [GET_SETTINGS_BY_PK_AND_SK, pk, sk],
|
|
94
|
+
queryFn: () => getSettingsByPkAndSKFun(pk, sk),
|
|
95
|
+
placeholderData: keepPreviousData,
|
|
96
|
+
staleTime: 1000 * 5 * 60,
|
|
97
|
+
enabled: pk !== "" && pk !== undefined && sk !== "" && sk !== undefined,
|
|
98
|
+
});
|
|
99
|
+
return {
|
|
100
|
+
settingsByPkAndSk: data,
|
|
101
|
+
settingsByPkAndSkError: error,
|
|
102
|
+
settingsByPkAndSkLoading: isLoading,
|
|
103
|
+
settingsByPkAndSkFetching: isFetching,
|
|
104
|
+
settingsByPkAndSkSuccess: isSuccess,
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
export const useUpdateSettingsMutation = () => {
|
|
108
|
+
async function createVersionFn(settingsData) {
|
|
109
|
+
const client = await Client.getClient();
|
|
110
|
+
const response = await client.graphql({
|
|
111
|
+
query: updateSettings,
|
|
112
|
+
variables: {
|
|
113
|
+
input: settingsData
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
return response;
|
|
117
|
+
}
|
|
118
|
+
const queryClient = useQueryClient();
|
|
119
|
+
return useMutation({
|
|
120
|
+
mutationFn: createVersionFn,
|
|
121
|
+
onSuccess: (_data, variables) => {
|
|
122
|
+
const settingsByPKQueryKey = [GET_SETTINGS_BY_PK, variables.pk];
|
|
123
|
+
queryClient.invalidateQueries({ queryKey: settingsByPKQueryKey });
|
|
124
|
+
const settingsByPKAndSKQueryKey = [GET_SETTINGS_BY_PK_AND_SK, variables.pk, variables.sk];
|
|
125
|
+
queryClient.invalidateQueries({ queryKey: settingsByPKAndSKQueryKey });
|
|
126
|
+
},
|
|
127
|
+
onError: (err) => {
|
|
128
|
+
logger.error("Error while settings updating", err);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
};
|
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
export declare const EnvConfig: {
|
|
2
2
|
env: any;
|
|
3
|
-
|
|
4
|
-
hmsapi: any;
|
|
3
|
+
appHostAPi: any;
|
|
5
4
|
region: any;
|
|
6
5
|
userPoolId: any;
|
|
7
6
|
userPoolClientId: any;
|
|
8
7
|
identityPoolId: any;
|
|
9
8
|
storage: any;
|
|
10
|
-
imageStorageBucketUrl: any;
|
|
11
|
-
keyId: any;
|
|
12
|
-
recordLimit: any;
|
|
13
|
-
authMode: any;
|
|
14
9
|
apiKey: any;
|
|
10
|
+
template: any;
|
|
11
|
+
imageStorageBucketUrl: any;
|
|
12
|
+
applicationName: any;
|
|
15
13
|
};
|
package/dist/config/EnvConfig.js
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
export const EnvConfig = {
|
|
2
2
|
env: import.meta.env.VITE_SERVER_ENV || "local",
|
|
3
|
-
|
|
4
|
-
hmsapi: import.meta.env.VITE_HMS_SERVICE_SERVER_URL || "",
|
|
3
|
+
appHostAPi: import.meta.env.VITE_HMS_SERVICE_SERVER_URL || "",
|
|
5
4
|
region: import.meta.env.VITE_AWS_REGION || "",
|
|
6
5
|
userPoolId: import.meta.env.VITE_USERPOOL_ID || "",
|
|
7
6
|
userPoolClientId: import.meta.env.VITE_USERPOOL_CLIENT_ID || "",
|
|
8
7
|
identityPoolId: import.meta.env.VITE_IDPOOL_ID || "",
|
|
9
8
|
storage: import.meta.env.VITE_STORAGE_NAME || "",
|
|
10
|
-
imageStorageBucketUrl: import.meta.env.VITE_IMAGE_STORAGE_BUCKET_URL || "",
|
|
11
|
-
keyId: import.meta.env.VITE_KEY_ID || "",
|
|
12
|
-
recordLimit: import.meta.env.VITE_RECORD_LIMIT || 1000,
|
|
13
|
-
authMode: import.meta.env.VITE_API_AUTHMODE,
|
|
14
9
|
apiKey: import.meta.env.VITE_API_KEY || undefined,
|
|
10
|
+
template: import.meta.env.VITE_TEMPLATE || undefined,
|
|
11
|
+
imageStorageBucketUrl: import.meta.env.VITE_IMAGE_STORAGE_BUCKET_URL || "",
|
|
12
|
+
applicationName: import.meta.env.VITE_APPLICATION_NAME || "",
|
|
15
13
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function withSyzyAuth<P extends object>(WrappedComponent: React.ComponentType<P>): (props: P) => import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useContext, useEffect, useState } from "react";
|
|
3
|
+
import AppContext from "../store/AppContext";
|
|
4
|
+
import LoginForm from "../components/Login/Login";
|
|
5
|
+
import { getCurrentUser } from "aws-amplify/auth";
|
|
6
|
+
import { AppActionEnum } from "../store/AppAction";
|
|
7
|
+
import { Client } from "../services/Client.Service";
|
|
8
|
+
import { fetchAuthSession } from 'aws-amplify/auth';
|
|
9
|
+
import { getComponentsByRoleOnly, getRolesMappingByUserIdAndEntityFun, useGetUserMappingByUserId } from "../api/mapping-api";
|
|
10
|
+
import { EntityTypes } from "../domain/type/EntityTypes";
|
|
11
|
+
import { Status } from "../domain/type/StatusEnum";
|
|
12
|
+
export function withSyzyAuth(WrappedComponent) {
|
|
13
|
+
const ComponentWithAuthenticator = (props) => {
|
|
14
|
+
const [currentUser, setCurrentUser] = useState();
|
|
15
|
+
const { user, dispatch } = useContext(AppContext) || { user: undefined, allowedComponents: undefined, dispatch: undefined };
|
|
16
|
+
const [_isLoggedIn, setIsLoggedIn] = useState(false);
|
|
17
|
+
const [_emailVerifiedStatus, setEmailVerifiedStatus] = useState("");
|
|
18
|
+
const [isSessionReady, setIsSessionReady] = useState(false);
|
|
19
|
+
useEffect(() => {
|
|
20
|
+
if (!user?.userName) {
|
|
21
|
+
setCurrentUser(null);
|
|
22
|
+
setIsSessionReady(false);
|
|
23
|
+
}
|
|
24
|
+
}, [user]);
|
|
25
|
+
const fetchSession = async () => {
|
|
26
|
+
try {
|
|
27
|
+
const session = await getCurrentUser();
|
|
28
|
+
const userInfo = await fetchAuthSession({ forceRefresh: true });
|
|
29
|
+
setEmailVerifiedStatus(userInfo.tokens?.idToken?.payload.email_verified?.toString() ?? "");
|
|
30
|
+
if (session) {
|
|
31
|
+
const userId = session.signInDetails?.loginId ?? session.username;
|
|
32
|
+
setCurrentUser(userId);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
setCurrentUser(null);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
setCurrentUser(null);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
useEffect(() => {
|
|
43
|
+
fetchSession();
|
|
44
|
+
}, []);
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
const stopResetScheduler = Client.startClientResetScheduler();
|
|
47
|
+
return () => stopResetScheduler();
|
|
48
|
+
}, []);
|
|
49
|
+
useEffect(() => {
|
|
50
|
+
setIsLoggedIn(!!user?.userName);
|
|
51
|
+
}, [user]);
|
|
52
|
+
const { userMappingByUserId } = useGetUserMappingByUserId(currentUser ?? "");
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
const updateSession = async () => {
|
|
55
|
+
if (!currentUser)
|
|
56
|
+
return;
|
|
57
|
+
const branchId = userMappingByUserId?.pk ?? "";
|
|
58
|
+
// Fetch roles of this user
|
|
59
|
+
const roleData = await getRolesMappingByUserIdAndEntityFun(branchId, currentUser, EntityTypes.ROLE);
|
|
60
|
+
const activeRoles = roleData.filter(r => r.status === Status.Active);
|
|
61
|
+
const roleNames = activeRoles.map(r => r.roleName);
|
|
62
|
+
// Fetch components for each active role
|
|
63
|
+
const compData = await Promise.all(activeRoles.map(role => getComponentsByRoleOnly(role.roleId)));
|
|
64
|
+
const allowedComponents = compData.flat().map(c => c.componentTitle);
|
|
65
|
+
// Build and dispatch user session
|
|
66
|
+
const userSession = {
|
|
67
|
+
userName: currentUser,
|
|
68
|
+
branchId,
|
|
69
|
+
roles: roleNames,
|
|
70
|
+
allowedComponents: [...new Set(allowedComponents)],
|
|
71
|
+
};
|
|
72
|
+
dispatch?.({ session: userSession, type: AppActionEnum.SignIn });
|
|
73
|
+
setIsSessionReady(true);
|
|
74
|
+
};
|
|
75
|
+
updateSession();
|
|
76
|
+
}, [currentUser, userMappingByUserId]);
|
|
77
|
+
// Login handler
|
|
78
|
+
const login = (loggedIn) => {
|
|
79
|
+
setIsLoggedIn(loggedIn);
|
|
80
|
+
if (loggedIn)
|
|
81
|
+
fetchSession();
|
|
82
|
+
};
|
|
83
|
+
return (_jsx("div", { children: currentUser === null ? _jsx(LoginForm, { login: login }) : _jsx(WrappedComponent, { ...props, isSessionReady: isSessionReady }) }));
|
|
84
|
+
};
|
|
85
|
+
return ComponentWithAuthenticator;
|
|
86
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { useContext } from "react";
|
|
2
|
+
import AppContext from "../store/AppContext";
|
|
3
|
+
import { defaultSession } from "../store/AppContextType";
|
|
4
|
+
export const useDispatch = () => {
|
|
5
|
+
const { dispatch } = useContext(AppContext) || { user: defaultSession };
|
|
6
|
+
return { dispatch };
|
|
7
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function AmIPermitted(componentName: string): boolean;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// hooks/usePermissions.ts
|
|
2
|
+
import { useContext } from "react";
|
|
3
|
+
import AppContext from "../store/AppContext";
|
|
4
|
+
export function AmIPermitted(componentName) {
|
|
5
|
+
const { user } = useContext(AppContext) || {};
|
|
6
|
+
return user?.allowedComponents?.includes(componentName) ?? false;
|
|
7
|
+
}
|
package/dist/main.js
CHANGED
|
@@ -3,7 +3,6 @@ import { StrictMode, useEffect, useState } from 'react';
|
|
|
3
3
|
import './index.css';
|
|
4
4
|
import 'bootstrap/dist/css/bootstrap.min.css';
|
|
5
5
|
import 'react-toastify/dist/ReactToastify.css';
|
|
6
|
-
// import AppProvider from './store/AppProvider.tsx';
|
|
7
6
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
8
7
|
// import { HostedInContainerProvider } from "./store/HostedInContainerContext.tsx";
|
|
9
8
|
import { ToastContainer } from 'react-toastify';
|
|
@@ -11,6 +10,7 @@ import { BrowserRouter as Router } from 'react-router-dom';
|
|
|
11
10
|
import './styles/typography.css';
|
|
12
11
|
import * as ReactDOM from 'react-dom/client';
|
|
13
12
|
import App from './App';
|
|
13
|
+
import AppProvider from './store/AppProvider';
|
|
14
14
|
function registerValidSW(swUrl, config) {
|
|
15
15
|
navigator.serviceWorker
|
|
16
16
|
.register(swUrl)
|
|
@@ -52,7 +52,7 @@ const AppWithServiceWorker = () => {
|
|
|
52
52
|
onUpdate: handleUpdate,
|
|
53
53
|
});
|
|
54
54
|
}, []);
|
|
55
|
-
return (_jsxs(StrictMode, { children: [_jsxs(QueryClientProvider, { client: queryClient, children: [_jsx(ToastContainer, { position: "top-right", autoClose: 3000, hideProgressBar: false, newestOnTop: true, closeOnClick: true, pauseOnHover: true, theme: "light", limit: 1 }), _jsx(Router, { children: _jsx(App, {}) })] }), showUpdatePrompt && (_jsxs("div", { className: "update-prompt", children: [_jsx("p", { children: "A new version of the app is available. Please refresh to update." }), _jsx("button", { onClick: () => {
|
|
55
|
+
return (_jsxs(StrictMode, { children: [_jsx(AppProvider, { children: _jsxs(QueryClientProvider, { client: queryClient, children: [_jsx(ToastContainer, { position: "top-right", autoClose: 3000, hideProgressBar: false, newestOnTop: true, closeOnClick: true, pauseOnHover: true, theme: "light", limit: 1 }), _jsx(Router, { children: _jsx(App, {}) })] }) }), showUpdatePrompt && (_jsxs("div", { className: "update-prompt", children: [_jsx("p", { children: "A new version of the app is available. Please refresh to update." }), _jsx("button", { onClick: () => {
|
|
56
56
|
swRegistration?.waiting?.postMessage({ type: 'SKIP_WAITING' });
|
|
57
57
|
window.location.reload();
|
|
58
58
|
}, children: "Refresh" })] }))] }));
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { uploadData } from 'aws-amplify/storage';
|
|
2
|
+
import { LogCategoryEnum } from '../util/LogEnum';
|
|
3
|
+
import { logger } from '../util/Logger';
|
|
4
|
+
import { EnvConfig } from '../config/EnvConfig';
|
|
5
|
+
export const getImageUrl = async (imageKey) => {
|
|
6
|
+
logger.debug(LogCategoryEnum.Info, "imageKey passed", imageKey);
|
|
7
|
+
let returnString = undefined;
|
|
8
|
+
if (imageKey) {
|
|
9
|
+
//Below for hms-ck-dev env image bucket url -------------
|
|
10
|
+
returnString = `${EnvConfig.imageStorageBucketUrl}/${imageKey}`;
|
|
11
|
+
}
|
|
12
|
+
return returnString;
|
|
13
|
+
};
|
|
14
|
+
export const uploadImage = async (imageKey, image) => {
|
|
15
|
+
logger.debug(LogCategoryEnum.Info, "inside upload image function", imageKey);
|
|
16
|
+
logger.debug(LogCategoryEnum.Info, "inside upload image function", image);
|
|
17
|
+
await uploadData({
|
|
18
|
+
key: imageKey,
|
|
19
|
+
data: image,
|
|
20
|
+
options: {
|
|
21
|
+
accessLevel: 'guest',
|
|
22
|
+
contentType: image.type,
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
logger.debug(LogCategoryEnum.Info, "image key", imageKey);
|
|
26
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { AppAction } from "./AppAction";
|
|
2
|
+
export interface AppSession {
|
|
3
|
+
userName: string;
|
|
4
|
+
branchId?: string;
|
|
5
|
+
roles: string[];
|
|
6
|
+
allowedComponents?: string[];
|
|
7
|
+
}
|
|
8
|
+
export declare const defaultSession: AppSession;
|
|
9
|
+
export interface AppContextProps {
|
|
10
|
+
user: AppSession;
|
|
11
|
+
dispatch: React.Dispatch<AppAction>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { defaultSession } from "./AppContextType";
|
|
3
|
+
import AppContext from "./AppContext";
|
|
4
|
+
import { ToastContainer } from 'react-toastify';
|
|
5
|
+
import 'react-toastify/dist/ReactToastify.css';
|
|
6
|
+
import { AppActionEnum } from "./AppAction";
|
|
7
|
+
import { sessionStorage } from "aws-amplify/utils";
|
|
8
|
+
import { APPHOSTSESSION_KEY, useSessionReducer } from "./SesssionReducer";
|
|
9
|
+
import { logger } from "../util/Logger";
|
|
10
|
+
const appContextReducer = (state, action) => {
|
|
11
|
+
logger.debug("Action:", action);
|
|
12
|
+
let newState = state;
|
|
13
|
+
switch (action.type) {
|
|
14
|
+
case AppActionEnum.SignIn:
|
|
15
|
+
newState = {
|
|
16
|
+
...action.session,
|
|
17
|
+
};
|
|
18
|
+
break;
|
|
19
|
+
case AppActionEnum.SignOut:
|
|
20
|
+
newState = { ...defaultSession };
|
|
21
|
+
sessionStorage.clear();
|
|
22
|
+
break;
|
|
23
|
+
default:
|
|
24
|
+
newState = state;
|
|
25
|
+
}
|
|
26
|
+
return newState;
|
|
27
|
+
};
|
|
28
|
+
const AppProvider = ({ children }) => {
|
|
29
|
+
const [state, dispatch] = useSessionReducer(appContextReducer, defaultSession, APPHOSTSESSION_KEY);
|
|
30
|
+
return (_jsxs(_Fragment, { children: [_jsx(ToastContainer, { position: "top-right", autoClose: 5000 }), _jsx(AppContext.Provider, { value: { user: state, dispatch }, children: children })] }));
|
|
31
|
+
};
|
|
32
|
+
export default AppProvider;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useContext } from 'react';
|
|
3
|
+
const HostedInContainerContext = createContext(false);
|
|
4
|
+
export const HostedInContainerProvider = ({ children }) => {
|
|
5
|
+
const isHosted = (() => {
|
|
6
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
7
|
+
return urlParams.get('hosted_in_container') === 'true';
|
|
8
|
+
})();
|
|
9
|
+
return (_jsx(HostedInContainerContext.Provider, { value: isHosted, children: children }));
|
|
10
|
+
};
|
|
11
|
+
export const useHostedInContainer = () => useContext(HostedInContainerContext);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { Reducer, Dispatch } from 'react';
|
|
2
|
+
import { AppSession } from './AppContextType';
|
|
3
|
+
export declare const APPHOSTSESSION_KEY = "AppHostSession";
|
|
4
|
+
export declare const useSessionReducer: <T extends AppSession, A>(reducer: Reducer<T, A>, initialState: T, storageKey: string) => [T, Dispatch<A>];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { useReducer, useEffect } from 'react';
|
|
2
|
+
export const APPHOSTSESSION_KEY = 'AppHostSession';
|
|
3
|
+
export const useSessionReducer = (reducer, initialState, storageKey) => {
|
|
4
|
+
const [state, dispatch] = useReducer(reducer, initialState, () => {
|
|
5
|
+
const value = localStorage.getItem(storageKey); // use storageKey here
|
|
6
|
+
let retState = { ...initialState };
|
|
7
|
+
if (value) {
|
|
8
|
+
retState = JSON.parse(value);
|
|
9
|
+
}
|
|
10
|
+
return retState;
|
|
11
|
+
});
|
|
12
|
+
useEffect(() => {
|
|
13
|
+
localStorage.setItem(storageKey, JSON.stringify(state)); // same key
|
|
14
|
+
}, [storageKey, state]);
|
|
15
|
+
return [state, dispatch];
|
|
16
|
+
};
|