phx-react
Version:
PHX REACT
628 lines • 39.7 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PHXMainWrapV4 = void 0;
const tslib_1 = require("tslib");
const fontawesome_svg_core_1 = require("@fortawesome/fontawesome-svg-core");
const free_solid_svg_icons_1 = require("@fortawesome/free-solid-svg-icons");
const react_1 = require("@headlessui/react");
const outline_1 = require("@heroicons/react/24/outline");
const solid_1 = require("@heroicons/react/24/solid");
const axios_1 = tslib_1.__importDefault(require("axios"));
const react_2 = tslib_1.__importStar(require("react"));
const appearance_styled_1 = tslib_1.__importDefault(require("./appearance/appearance-styled"));
const CallbackUrlSetter_1 = tslib_1.__importDefault(require("./components/CallbackUrlSetter"));
const left_heder_section_1 = tslib_1.__importDefault(require("./components/left-heder-section"));
const main_content_1 = tslib_1.__importDefault(require("./components/main-content"));
const notification_1 = tslib_1.__importDefault(require("./components/notification"));
const useNotificationUnreadPolling_1 = require("./components/notification/hook/useNotificationUnreadPolling");
const search_1 = tslib_1.__importDefault(require("./components/search"));
const side_bar_1 = tslib_1.__importDefault(require("./components/side-bar"));
const submenu_1 = tslib_1.__importDefault(require("./components/submenu"));
const constant_1 = require("./constant");
const nav_mobile_1 = tslib_1.__importDefault(require("./navigator/nav-mobile"));
const getCookieSession_1 = tslib_1.__importDefault(require("../Func/getCookieSession"));
const LoadingProvider_1 = require("../LoadingProvider");
const constants_1 = require("../../utils/constants");
const sessionStore_1 = require("../Func/sessionStore");
const deleteCookie_1 = require("../Func/deleteCookie");
const save_local_storage_1 = require("../Func/save-local-storage");
const PHXGrpcClientV3_1 = require("../Func/GRPC/PHXGrpcClientV3");
const query_1 = require("../../query");
const getEnvPublic_1 = tslib_1.__importDefault(require("../Func/getEnvPublic"));
const saveCookiesClient_1 = tslib_1.__importDefault(require("../Func/saveCookiesClient"));
const helpers_1 = require("../../helpers/helpers");
const Modal_1 = require("../Modal");
const types_1 = require("../types");
const PHXGrpcClientV6_1 = require("../Func/GRPC/PHXGrpcClientV6");
const page_tracker_1 = require("../../stores/page-tracker/page-tracker");
const required_action_api_1 = require("./components/require-action/required-action-api");
const required_action_1 = require("./components/require-action/required-action");
const use_mainwrap_realtime_counts_1 = require("./hooks/use-mainwrap-realtime-counts");
fontawesome_svg_core_1.library.add(free_solid_svg_icons_1.fas);
// Option hiển thị required action count cho menu
const REQUIRED_ACTION_MENU_CONFIG = {
// Bật để xem mock UI khi API chưa trả count
useMockFallbackWhenMissing: false,
fallbackCount: 100,
// 'all': hiện count cả menu cha + menu con
// 'leaf-only': chỉ hiện ở menu nhỏ nhất
displayMode: 'all',
// Khi API chỉ trả count theo code menu lá, bật true để cộng dồn lên menu cha
aggregateToParent: true,
// API/backend sẽ xử lý roll-up; frontend chỉ map count theo code menu
aggregateByCodeLevel: false,
codeLevels: [],
};
const PHXMainWrapV4 = ({ children, getDataCookies, logoHeight = '28px', multipleMenu = false, params, pathName, router, }) => {
var _a, _b, _c, _d;
const { pid } = params ? params : {};
const [sidebarOpen, setSidebarOpen] = (0, react_2.useState)(false);
const [subNavigation, setSubNavigation] = (0, react_2.useState)([]);
const [navigation, setNavigation] = (0, react_2.useState)([]);
const [modalSignOut, setModalSignOut] = (0, react_2.useState)(false);
const [isLoading, setIsLoading] = (0, react_2.useState)(true);
const sessionCookie = (0, getCookieSession_1.default)();
const userSessionInfo = sessionCookie === null || sessionCookie === void 0 ? void 0 : sessionCookie.user_info;
const schoolInfoId = userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.school_id;
const userId = userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.id;
const { setLoading: setGlobalLoading } = (0, LoadingProvider_1.useLoading)();
const [showSubMenu, setShowSubMenu] = (0, react_2.useState)(true);
const [mounted, setMounted] = (0, react_2.useState)(false);
const contentRef = (0, react_2.useRef)(null);
const [sideBarType, setSideBarType] = (0, react_2.useState)(constant_1.SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL);
const [dataInitMain, setDataInitMain] = (0, react_2.useState)({
menuDefault: [],
loadingMenu: true,
loadingSchool: true,
listSchool: [],
logo: {
path: '',
height: logoHeight,
},
menu: [],
schoolId: null,
configLayout: undefined,
perCode: [],
roleCode: [],
isLoadingPermission: true,
sourceAvatar: ((_a = userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.user_avatar) === null || _a === void 0 ? void 0 : _a.size_small) || (userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.avatar) || constants_1.DEFAULT_AVATAR,
});
const [isRealtimeSocketConnected, setIsRealtimeSocketConnected] = (0, react_2.useState)(false);
const accessToken = sessionCookie === null || sessionCookie === void 0 ? void 0 : sessionCookie.access_token;
const enableUnreadPollingFallback = !mounted || !accessToken || !isRealtimeSocketConnected;
const { applyUnreadCount, unreadCount } = (0, useNotificationUnreadPolling_1.useNotificationUnreadPolling)(5000, enableUnreadPollingFallback);
const locationPathname = typeof window !== 'undefined' ? window.location.pathname : '';
const locationArr = locationPathname.split('/').filter(Boolean);
const basePath = locationArr.slice(0, locationArr.length - pathName.split('/').filter(Boolean).length).join('/');
const pathNameWithBasePath = `${basePath ? `${'/' + basePath}` : ''}${pathName}`;
// Lấy code phân quyền trong menu từ path hiện tại
function getCodesByPath(dataMenu, currentPath) {
let lastMatchingCode = null;
const normalizedPath = currentPath.replace(/\/$/, '');
function traverse(items, prefix) {
for (const item of items) {
const fullPath = item.path.startsWith('/') ? prefix + item.path : item.path;
const normalizedFullPath = fullPath.replace(/\/$/, '');
if (normalizedPath === normalizedFullPath || normalizedPath.startsWith(normalizedFullPath + '/')) {
lastMatchingCode = item.code;
}
if (item.child) {
traverse(item.child, prefix);
}
}
}
for (const rootItem of dataMenu) {
const rootPath = rootItem.path;
const prefix = rootPath.split('/').slice(0, 2).join('/');
traverse([rootItem], prefix);
}
return lastMatchingCode ? lastMatchingCode : null;
}
// code phân quyền path hiện tại
const currentCode = getCodesByPath(dataInitMain.menuDefault, locationPathname);
const currentMenuByPath = navigation === null || navigation === void 0 ? void 0 : navigation.find((nav) => { var _a; return (_a = nav === null || nav === void 0 ? void 0 : nav.child) === null || _a === void 0 ? void 0 : _a.some((c) => { var _a; return (c === null || c === void 0 ? void 0 : c.code) === currentCode || ((_a = c === null || c === void 0 ? void 0 : c.child) === null || _a === void 0 ? void 0 : _a.some((x) => (x === null || x === void 0 ? void 0 : x.code) === currentCode)); }); });
const requireLoginValidation = () => {
(0, sessionStore_1.clearSession)();
const currentURL = window.location.href;
const url = currentURL.split('/');
const loginPush = `${url[0]}//${url[2]}/login-sso`;
window.location.replace(loginPush);
};
const checkIsQuitJob = ({ profileStaff, profileTeacher }) => {
try {
// xóa cookies với những tài khoản giáo viên, nhân viên đã nghỉ việc
const staffIsQuitJob = profileStaff === null || profileStaff === void 0 ? void 0 : profileStaff.is_quit_job;
const teacherIsQuitJob = profileTeacher === null || profileTeacher === void 0 ? void 0 : profileTeacher.is_quit_job;
if (staffIsQuitJob || teacherIsQuitJob) {
console.log('Phiên đăng nhập đã hết hạn');
(0, deleteCookie_1.deleteAllCookies)();
(0, save_local_storage_1.deleteLocalStorage)(constants_1.COOKIE_SESSION_SIGN_IN);
requireLoginValidation();
}
}
catch (error) {
console.log(error);
}
};
const fetchDataPer = async () => {
var _a, _b, _c, _d;
try {
const res = await (0, PHXGrpcClientV3_1.PHXClientQueryV3)({
query: query_1.GET_PERMISSION_DETAIL_USER_V3,
variables: { id: userId, school_id: schoolInfoId },
});
const userPermissions = (_b = (_a = res.data) === null || _a === void 0 ? void 0 : _a.permission_user) !== null && _b !== void 0 ? _b : [];
const rolePermissions = (_d = (_c = res.data) === null || _c === void 0 ? void 0 : _c.permission_role) !== null && _d !== void 0 ? _d : [];
const allPermissions = [...userPermissions, ...rolePermissions];
// Tách quyền theo loại: quyền route (không phải action) và quyền action
const permissionCodes = allPermissions.map((p) => p.permission);
const routePermissions = permissionCodes.filter((p) => !p.is_action).map((p) => p.code);
const actionPermissions = permissionCodes.filter((p) => p.is_action).map((p) => p.code);
// Tạo object dạng { ACTION_CODE: true }
const actionPermissionMap = Object.fromEntries(actionPermissions.map((code) => [code, true]));
// Xoá trùng và set route permissions
const uniqueRoutePermissions = Array.from(new Set(routePermissions));
return { uniqueRoutePermissions, actionPermissionMap };
}
catch (error) {
console.error('Error fetching school data:', error);
return { uniqueRoutePermissions: null, actionPermissionMap: null };
}
};
const getProfileByUser = async () => {
try {
const response = await (0, PHXGrpcClientV3_1.PHXClientQueryV3)({
query: query_1.QUERY_GET_PROFILE_USER,
variables: {
user_id: userId,
},
});
const profileUser = response.data.users_by_pk;
const { avatar, email, full_name, profile_staff, profile_teacher, user_avatar, user_roles } = profileUser;
// check user is quit job
checkIsQuitJob({
profileStaff: profile_staff,
profileTeacher: profile_teacher,
});
// renew list role in cookie
return {
avatar,
user_avatar,
full_name,
email,
user_code: (profile_staff === null || profile_staff === void 0 ? void 0 : profile_staff.user_code) || (profile_teacher === null || profile_teacher === void 0 ? void 0 : profile_teacher.user_code) || '',
user_roles,
};
}
catch (error) {
console.log(error);
return;
}
};
const fidSettingSiteBySchool = (settings, schoolId) => settings === null || settings === void 0 ? void 0 : settings.find((setting) => setting.school_id === schoolId);
const fetchDataSchool = async () => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
if (!userSessionInfo)
return;
const { email, school: { school_name: { group_id }, school_name_id, }, school_id, } = userSessionInfo;
setIsLoading(true);
let settingSiteDb = undefined;
try {
const res = await (0, PHXGrpcClientV3_1.PHXGrpcQueryAllSchool)({
query: query_1.GET_SCHOOL_V3,
variables: { group_id, school_name_id, email },
isDelay: false,
isQuery: true,
});
const userIds = ((_c = (_b = (_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.school) === null || _b === void 0 ? void 0 : _b.flatMap((s) => { var _a; return (_a = s.users) === null || _a === void 0 ? void 0 : _a.map((u) => u.id); })) === null || _c === void 0 ? void 0 : _c.filter(Boolean)) || [];
let resGraphile = null;
if (userIds.length > 0) {
resGraphile = await (0, PHXGrpcClientV6_1.PHXGrpcQueryAllSchoolV6)({
query: query_1.GET_CROSS_SCHOOL_ACCESS_V3,
variables: { userIds },
isDelay: false,
schemaGroup: 'core-shared',
});
}
let dataSchool = (_e = (_d = res === null || res === void 0 ? void 0 : res.data) === null || _d === void 0 ? void 0 : _d.school_name[0]) === null || _e === void 0 ? void 0 : _e.schools;
const settingSites = (_f = res === null || res === void 0 ? void 0 : res.data) === null || _f === void 0 ? void 0 : _f.setting_site;
const canSwitchSchool = ((_j = (_h = (_g = resGraphile === null || resGraphile === void 0 ? void 0 : resGraphile.data) === null || _g === void 0 ? void 0 : _g.allCoreSharedPermissionCrossSchoolAccesses) === null || _h === void 0 ? void 0 : _h.nodes) === null || _j === void 0 ? void 0 : _j.length) > 0;
if (canSwitchSchool) {
dataSchool =
((_l = (_k = resGraphile.data.allCoreSharedPermissionCrossSchoolAccesses) === null || _k === void 0 ? void 0 : _k.nodes) === null || _l === void 0 ? void 0 : _l.map((node) => {
var _a, _b, _c, _d, _e;
const school = node.coreSharedPublicSchoolBySchoolId;
const logo = (_b = (_a = fidSettingSiteBySchool(settingSites, school === null || school === void 0 ? void 0 : school.rowId)) === null || _a === void 0 ? void 0 : _a.value_setting) === null || _b === void 0 ? void 0 : _b.replace(/^"(.*)"$/, '$1');
return {
id: (school === null || school === void 0 ? void 0 : school.rowId) || node.schoolId,
name: school === null || school === void 0 ? void 0 : school.name,
school_name: {
id: (_c = school === null || school === void 0 ? void 0 : school.coreSharedPublicSchoolNameBySchoolNameIdAndSchoolId) === null || _c === void 0 ? void 0 : _c.rowId,
group_id: (_d = school === null || school === void 0 ? void 0 : school.coreSharedPublicSchoolNameBySchoolNameIdAndSchoolId) === null || _d === void 0 ? void 0 : _d.groupId,
},
userId: node.userId,
logo: logo ? (_e = JSON.parse(logo)) === null || _e === void 0 ? void 0 : _e.logo_dashboard : null,
};
})) || [];
}
const settingFetchData = (_m = fidSettingSiteBySchool(settingSites, school_id)) === null || _m === void 0 ? void 0 : _m.value_setting;
if (settingFetchData) {
const cleanedJsonString = settingFetchData.replace(/^"(.*)"$/, '$1');
settingSiteDb = JSON.parse(cleanedJsonString);
}
setIsLoading(false);
return {
settingSiteDb,
loadingSchool: dataSchool.length === 0,
listSchool: dataSchool,
schoolId: school_id,
};
}
catch (error) {
setIsLoading(false);
console.error('Error fetching school data:', error);
return;
}
};
const fetchDataMenu = async () => {
const envPublic = await (0, getEnvPublic_1.default)();
const menuUrl = envPublic === null || envPublic === void 0 ? void 0 : envPublic.SCHOOL_MENU_V2;
const logoMenuTop = envPublic === null || envPublic === void 0 ? void 0 : envPublic.SCHOOL_TOP_MENU_LOGO;
if (!menuUrl || !logoMenuTop) {
console.error('menu or logo not found');
}
const data = await fetch(menuUrl, {
cache: 'no-store', // tắt cache menu
});
const menuJson = await data.json();
return {
loadingMenu: false,
logo: { path: logoMenuTop, height: logoHeight },
menu: menuJson,
};
};
const detectEnvByDomain = (domain, configEnv) => {
for (const [env, pattern] of Object.entries(configEnv)) {
if (env.startsWith('_comment'))
continue; // bỏ qua comment
const regex = new RegExp(pattern.replace(/\\\\/g, '\\'));
if (regex.test(domain))
return env;
}
return 'stg';
};
const getEnvByConfig = (configEnv) => {
const domain = window.location.hostname;
const env = detectEnvByDomain(domain, configEnv);
return `config_menu_${env}:disable`;
};
const isConfigEnvValid = (code, configDisable) => configDisable.length === 0 || !(configDisable === null || configDisable === void 0 ? void 0 : configDisable.includes(code));
const funcMenuByConfigEnv = (menuJson, configDisable) => {
const menuWithConfigEnv = [];
for (const item of menuJson) {
if (!isConfigEnvValid(item === null || item === void 0 ? void 0 : item.code, configDisable))
continue;
const menuItem = { ...item, child: [] };
const menuSecondLevel = (item === null || item === void 0 ? void 0 : item.child) || [];
for (const childItem of menuSecondLevel || []) {
if (!isConfigEnvValid(childItem === null || childItem === void 0 ? void 0 : childItem.code, configDisable))
continue;
const childMenuItem = { ...childItem, child: [] };
const menuThirdLevel = (childItem === null || childItem === void 0 ? void 0 : childItem.child) || [];
for (const subChildItem of menuThirdLevel) {
if (!isConfigEnvValid(subChildItem === null || subChildItem === void 0 ? void 0 : subChildItem.code, configDisable))
continue;
childMenuItem.child.push(subChildItem);
}
menuItem.child.push(childMenuItem);
}
menuWithConfigEnv.push(menuItem);
}
return menuWithConfigEnv;
};
const fetchInitData = async () => {
var _a;
const { loadingMenu, logo, menu } = await fetchDataMenu();
const requiredActionData = await (0, required_action_api_1.fetchRequiredActionData)();
const profileNew = await getProfileByUser();
const dataPer = await fetchDataPer();
const { actionPermissionMap, uniqueRoutePermissions } = dataPer;
const dataSchool = await fetchDataSchool();
const { config_env } = menu;
const enviromentByDomainConfig = getEnvByConfig(config_env);
const menuJson = menu.menu;
const configDisable = menu[enviromentByDomainConfig];
const menuWithConfigEnv = funcMenuByConfigEnv(menuJson, configDisable);
const menuWithRequiredAction = (0, required_action_1.applyRequiredActionCount)(menuWithConfigEnv, requiredActionData.countByCode, REQUIRED_ACTION_MENU_CONFIG);
setDataInitMain({
menuDefault: menuJson,
logo,
menu: menuWithRequiredAction,
loadingMenu,
schoolId: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.schoolId) || null,
loadingSchool: !!(dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.loadingSchool),
listSchool: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.listSchool) || [],
isLoadingPermission: false,
perCode: uniqueRoutePermissions,
roleCode: (profileNew === null || profileNew === void 0 ? void 0 : profileNew.user_roles.map((userRole) => { var _a; return (_a = userRole === null || userRole === void 0 ? void 0 : userRole.role) === null || _a === void 0 ? void 0 : _a.role_code; })) || [],
configLayout: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.settingSiteDb) || undefined,
sourceAvatar: ((_a = profileNew === null || profileNew === void 0 ? void 0 : profileNew.user_avatar) === null || _a === void 0 ? void 0 : _a.size_small) || (profileNew === null || profileNew === void 0 ? void 0 : profileNew.avatar) || constants_1.DEFAULT_AVATAR,
});
const currentSession = (0, getCookieSession_1.default)();
(0, saveCookiesClient_1.default)({
value: {
...currentSession,
...(actionPermissionMap && {
action_permission: actionPermissionMap || [],
}),
setting_site: (dataSchool === null || dataSchool === void 0 ? void 0 : dataSchool.settingSiteDb) || {},
...(profileNew && {
user_info: {
...userSessionInfo,
...profileNew,
},
}),
},
});
};
const isEqualUrl = (parentHref, pathNameCompare) => {
if (!parentHref || !pathNameCompare) {
return false;
}
const pathNameSplit = pathNameCompare.split('/');
const hrefSplit = parentHref.split('/');
if (!pathNameSplit || !hrefSplit) {
return false;
}
let urlRouter;
let currentMenu;
if (multipleMenu) {
urlRouter = pathNameSplit[1] + pathNameSplit[2];
currentMenu = hrefSplit[1] + hrefSplit[2];
}
else {
urlRouter = pathNameSplit[1];
currentMenu = hrefSplit[1];
}
return urlRouter === currentMenu;
};
const isBelongParentWithMicroservice = (parentSplit, pathNameSplit) => {
if (parentSplit.length > 2) {
const compareLength = parentSplit.length;
for (let i = 1; i < compareLength; i++) {
if (parentSplit[i] !== pathNameSplit[i])
return false;
}
return true;
}
else {
return parentSplit[1] === pathNameSplit[3];
}
};
const isBelongParent = (parentUrl, pathNameCompare, isMicroservice) => {
const parentSplit = parentUrl.split('/');
const pathNameSplit = pathNameCompare.split('/');
if (isMicroservice) {
return isBelongParentWithMicroservice(parentSplit, pathNameSplit);
}
if (parentSplit.length > 2 && !parentSplit.includes('list')) {
return parentSplit[1] === pathNameSplit[2] && parentSplit[2] === pathNameSplit[3];
}
else {
return parentSplit[1] === pathNameSplit[2];
}
};
const loadParentNavigation = (path) => {
const mainNavigation = dataInitMain.menu;
const naviSize = mainNavigation.length;
for (let i = 0; i < naviSize; i++) {
const item = mainNavigation[i];
item.current = false;
if (item.path === path || isEqualUrl(item.path, path)) {
item.current = true;
// Find sub modules
const itemLength = item.child.length;
const listChildren = [];
for (let j = 0; j < itemLength; j++) {
const childItem = item.child[j];
// Active child item
childItem.current = isBelongParent(childItem.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice));
if (childItem.child) {
const childItemLength = childItem.child.length;
let count = 0;
for (let k = 0; k < childItemLength; k++) {
const subChild = childItem.child[k];
subChild.current = isBelongParent(subChild.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice));
if (isBelongParent(subChild.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice)) ||
isBelongParent(childItem.path, path, !!(childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice))) {
count++;
}
const isSameSubChildPath = (subChild === null || subChild === void 0 ? void 0 : subChild.isMicroservice)
? subChild.path === (childItem === null || childItem === void 0 ? void 0 : childItem.path)
: subChild.path === (childItem === null || childItem === void 0 ? void 0 : childItem.pathInternal);
const isPathInternal = (childItem === null || childItem === void 0 ? void 0 : childItem.isMicroservice) ? isSameSubChildPath : subChild.path === childItem.path;
childItem.showChild = count > 0;
if (isPathInternal)
childItem.current = false;
}
}
listChildren.push(childItem);
}
setSubNavigation(listChildren);
}
}
setNavigation(mainNavigation);
};
const loadSubNavigation = (path, isChild, childPath) => {
const subLength = subNavigation.length;
const newSub = [];
for (let i = 0; i < subLength; i++) {
const item = subNavigation[i];
item.current = item.path === path && !isChild;
if (item.child) {
item.showChild = item.path === path;
for (let j = 0; j < item.child.length; j++) {
const child = item.child[j];
child.current = child.path === childPath;
if (child.path === item.path) {
item.current = false;
child.current = childPath ? child.path === childPath : child.path === path;
}
}
}
newSub.push(item);
}
setSubNavigation(newSub);
};
const subNavigationTriggerClicked = (item, parent) => {
if (parent) {
loadSubNavigation(parent.path, true, item.path);
}
else {
loadSubNavigation(item.path, false);
}
if (pathName !== item.path) {
setGlobalLoading(true);
}
router.push(item.path);
};
const { path: topMenuLogoFromEnv } = dataInitMain.logo;
const handleModalSignOut = () => setModalSignOut(true);
const handleRedirectRouter = (path) => {
const currentURL = window.location.href;
const url = currentURL.split('/');
const pushPath = `${url[0]}//${url[2]}/${path}`;
window.location.replace(pushPath);
};
const callApiLogoutToken = async () => {
try {
return await axios_1.default.post(`/api/authenticate/logout`, {}, {
withCredentials: true,
});
}
catch (error) {
console.error(error);
return;
}
};
const handleSignOut = async () => {
setModalSignOut(false);
(0, deleteCookie_1.deleteAllCookies)();
(0, save_local_storage_1.deleteLocalStorage)(constants_1.COOKIE_SESSION_SIGN_IN);
await callApiLogoutToken();
handleRedirectRouter('login-sso');
};
const handleProfilePage = () => {
handleRedirectRouter('profile');
};
const isSettingPage = ((_b = pathNameWithBasePath === null || pathNameWithBasePath === void 0 ? void 0 : pathNameWithBasePath.split('/')) === null || _b === void 0 ? void 0 : _b[1]) === 'setting';
const checkLogoHeader = ((_c = dataInitMain.configLayout) === null || _c === void 0 ? void 0 : _c.logo_dashboard) || topMenuLogoFromEnv || constants_1.DEFAULT_LOGO_DASHBOARD;
const isActivityHistory = () => {
const pathNameSplit = pathNameWithBasePath.split('/');
return pathNameSplit[1] === constants_1.PATH_ACTIVITY_HISTORY;
};
const [activityHistoryChild, setActivityHistoryChild] = (0, react_2.useState)(constants_1.MENU_ACTIVITY_HISTORY_CHILD);
const handleClickActivityHistoryChild = (clickedItem) => {
const updated = activityHistoryChild.map((item) => ({
...item,
current: item.code === clickedItem.code,
}));
setActivityHistoryChild(updated);
};
const onChangeSideBarType = (type) => {
setSideBarType(type);
localStorage.setItem(constant_1.LOCALSTORAGE_SHOW_SIDEBAR_TYPE, type);
};
(0, react_2.useEffect)(() => {
if (basePath === constants_1.PATH_ACTIVITY_HISTORY) {
setActivityHistoryChild((prev) => prev.map((item) => ({
...item,
current: pathNameWithBasePath.endsWith(item.path),
})));
}
else {
setActivityHistoryChild([]);
}
}, [pathNameWithBasePath, basePath]);
(0, react_2.useEffect)(() => {
loadParentNavigation(pathNameWithBasePath);
}, [dataInitMain, pid, pathNameWithBasePath]);
(0, react_2.useEffect)(() => {
if (!userSessionInfo) {
// Require login if production mode
requireLoginValidation();
return;
}
setMounted(true);
setShowSubMenu(JSON.parse(localStorage.getItem(constant_1.LOCALSTORAGE_SHOW_SUB_MENU_KEY) || 'true'));
setSideBarType(localStorage.getItem(constant_1.LOCALSTORAGE_SHOW_SIDEBAR_TYPE) || constant_1.SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL);
fetchInitData();
}, []);
(0, react_2.useEffect)(() => {
if (mounted) {
localStorage.setItem(constant_1.LOCALSTORAGE_SHOW_SUB_MENU_KEY, JSON.stringify(showSubMenu));
}
}, [showSubMenu, mounted]);
const handleSocketRequiredAction = (0, react_2.useCallback)(({ countByCode }) => {
setDataInitMain((prev) => {
var _a;
if (!((_a = prev.menu) === null || _a === void 0 ? void 0 : _a.length))
return prev;
const nextMenu = (0, required_action_1.applyRequiredActionCount)(prev.menu, countByCode, REQUIRED_ACTION_MENU_CONFIG);
return { ...prev, menu: nextMenu };
});
}, []);
const handleSocketConnectionChange = (0, react_2.useCallback)((connected) => {
setIsRealtimeSocketConnected(connected);
}, []);
(0, use_mainwrap_realtime_counts_1.useMainwrapRealtimeCounts)({
accessToken,
currentUserId: userId,
enabled: mounted,
onConnectionChange: handleSocketConnectionChange,
onRequiredAction: handleSocketRequiredAction,
onUnreadCount: applyUnreadCount,
});
return (mounted && (react_2.default.createElement(react_2.default.Fragment, null,
react_2.default.createElement(page_tracker_1.PageTracker, null),
react_2.default.createElement(react_2.Suspense, { fallback: null },
react_2.default.createElement(CallbackUrlSetter_1.default, { path: pathNameWithBasePath })),
react_2.default.createElement("div", { className: 'flex h-12 flex-col bg-[#DEDEDE]' },
react_2.default.createElement(appearance_styled_1.default, { configLayout: dataInitMain === null || dataInitMain === void 0 ? void 0 : dataInitMain.configLayout, settingSiteCookie: getDataCookies ? (_d = (0, helpers_1.decryptCookie)(getDataCookies)) === null || _d === void 0 ? void 0 : _d.setting_site : null }),
react_2.default.createElement("header", { className: 'fixed top-0 z-[50] flex h-12 min-w-full flex-col justify-between pl-1.5 pr-2 lg:px-5 bg-[#DEDEDE] lg:bg-transparent' },
react_2.default.createElement("div", { className: 'flex h-12 w-full items-center justify-between' },
react_2.default.createElement("div", { className: 'flex items-center gap-x-2' },
react_2.default.createElement("div", { className: 'flex items-center lg:hidden' },
react_2.default.createElement("button", { className: 'bg-grey-100 inline-flex items-center justify-center rounded-md p-1 text-gray-200 hover:bg-white hover:text-gray-600', onClick: () => setSidebarOpen(!sidebarOpen), type: 'button' },
react_2.default.createElement("span", { className: 'sr-only' }, "Open sidebar"),
sidebarOpen ? (react_2.default.createElement(solid_1.XMarkIcon, { "aria-hidden": 'true', className: 'h-5 w-5 text-gray-900' })) : (react_2.default.createElement(outline_1.Bars3Icon, { "aria-hidden": 'true', className: 'h-5 w-5 text-gray-900' })))),
!isLoading && (react_2.default.createElement(left_heder_section_1.default, { checkLogoHeader: checkLogoHeader, currSchoolId: dataInitMain.schoolId, perCodes: dataInitMain.perCode, schools: dataInitMain.listSchool, topMenuLogoFromEnv: topMenuLogoFromEnv }))),
react_2.default.createElement(search_1.default, { contentRef: contentRef, menu: navigation, perCode: dataInitMain.perCode, sideBarType: sideBarType, unreadCount: unreadCount, userId: userId }),
react_2.default.createElement("div", { className: 'flex items-center gap-2' },
react_2.default.createElement(notification_1.default, { unreadCount: unreadCount }),
react_2.default.createElement("div", null,
react_2.default.createElement(react_1.Menu, { as: 'div', className: 'relative' },
react_2.default.createElement("div", null,
react_2.default.createElement(react_1.Menu.Button, { className: 'flex max-w-xs items-center rounded-full bg-gray-800 text-sm focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800' },
react_2.default.createElement("span", { className: 'sr-only' }, "Open user menu"),
isLoading ? (react_2.default.createElement("div", { className: 'flex animate-pulse' },
react_2.default.createElement("div", { className: 'header-loading-avatar h-6 w-6 rounded-full' }))) : (react_2.default.createElement("img", { alt: '', className: 'h-6 w-6 rounded-full', src: dataInitMain.sourceAvatar })))),
react_2.default.createElement(react_1.Transition, { as: react_2.Fragment, enter: 'transition ease-out duration-100', enterFrom: 'transform opacity-0 scale-95', enterTo: 'transform opacity-100 scale-100', leave: 'transition ease-in duration-75', leaveFrom: 'transform opacity-100 scale-100', leaveTo: 'transform opacity-0 scale-95' },
react_2.default.createElement(react_1.Menu.Items, { className: ' shadow-lg absolute right-0 z-10 mt-2 w-[340px] origin-top-right rounded-md bg-white px-2 ring-1 ring-black ring-opacity-5 focus:outline-none' },
react_2.default.createElement(react_1.Menu.Item, null,
react_2.default.createElement("div", { "aria-hidden": true, className: 'px-2 pb-2 pt-4 text-sm font-semibold text-gray-900' }, "T\u00F9y ch\u1ECDn")),
react_2.default.createElement(react_1.Menu.Item, null,
react_2.default.createElement("div", { "aria-hidden": true, className: 'cursor-pointer px-2 py-1.5 text-sm text-gray-900 hover:rounded-lg hover:bg-gray-100', onClick: handleProfilePage }, "Th\u00F4ng tin c\u00E1 nh\u00E2n")),
react_2.default.createElement(react_1.Menu.Item, null,
react_2.default.createElement("div", { "aria-hidden": true, className: 'mb-2.5 cursor-pointer px-2 py-1.5 text-sm text-[#8e1f0c] hover:rounded-lg hover:bg-gray-100', onClick: handleModalSignOut }, "\u0110\u0103ng xu\u1EA5t")))))))))),
react_2.default.createElement(Modal_1.PHXModal, { dangerActionText: '\u0110\u0103ng xu\u1EA5t', onDangerClick: handleSignOut, onHide: () => setModalSignOut(false), primaryActionText: '', show: modalSignOut, title: '\u0110\u0103ng xu\u1EA5t' },
react_2.default.createElement("div", { className: 'text-sm text-gray-700' }, "Khi th\u1EF1c hi\u1EC7n thao t\u00E1c n\u00E0y b\u1EA1n s\u1EBD tho\u00E1t kh\u1ECFi trang qu\u1EA3n tr\u1ECB v\u00E0 tr\u1EDF v\u1EC1 trang \u0111\u0103ng nh\u1EADp")),
react_2.default.createElement("div", { className: (0, types_1.classNames)('relative h-screen bg-[#DEDEDE] pb-[0.5rem] lg:flex lg:h-[calc(100vh-3rem)] lg:flex-col lg:overflow-hidden', sideBarType === constant_1.SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL ? 'lg:!pl-4' : 'lg:!pl-2') },
react_2.default.createElement("div", { className: 'h-full lg:flex' },
react_2.default.createElement(nav_mobile_1.default, { hiddenSideBar: () => setSidebarOpen(false), menu: dataInitMain.menu, path: pathNameWithBasePath, pathNameWithBasePath: pathNameWithBasePath, permission: dataInitMain.perCode, router: router, setSidebarOpen: setSidebarOpen, sidebarOpen: sidebarOpen }),
react_2.default.createElement(side_bar_1.default, { currentMenuCode: (currentMenuByPath === null || currentMenuByPath === void 0 ? void 0 : currentMenuByPath.code) || '', dataInitMain: dataInitMain, isActivityHistory: isActivityHistory(), isSettings: isSettingPage, navigation: navigation, onChangeSideBarType: onChangeSideBarType, setShowSubMenu: setShowSubMenu, showSubMenu: showSubMenu, sideBarType: sideBarType, userId: userId }),
react_2.default.createElement(submenu_1.default, { activityHistoryChild: activityHistoryChild, currentMenuByPath: currentMenuByPath, handleClickActivityHistoryChild: handleClickActivityHistoryChild, isActivityHistory: isActivityHistory(), isShowSubmenu: showSubMenu, loadingMenu: dataInitMain.loadingMenu, perCode: dataInitMain.perCode, roleCodes: dataInitMain.roleCode, setShowSubMenu: setShowSubMenu, sideBarType: sideBarType, subNavigation: subNavigation, subNavigationTriggerClicked: subNavigationTriggerClicked }),
react_2.default.createElement(main_content_1.default, { contentRef: contentRef, currentCode: currentCode || '', isLoadingPermission: dataInitMain.isLoadingPermission, perCode: dataInitMain.perCode, showSubMenu: showSubMenu, sideBarType: sideBarType }, children))))));
};
exports.PHXMainWrapV4 = PHXMainWrapV4;
//# sourceMappingURL=MainWrapV4.js.map