Rapport-Mobileapp/src/App-bk-apr-2026.jsx

642 lines
22 KiB
JavaScript

import { useState, useEffect } from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
//Utility
import { handleThemeChange, handleAlert } from "./util/util";
import { handleNotificationClick } from "./components/Notifications/notificationsUtil";
import { refreshToken } from "./services/authUtility";
//Layouts
import DashboardLayout from "./layouts/DashboardLayout";
//Pages
import AppIcons from "./pages/AppIcons";
import HomeGuest from "./pages/HomeGuest";
import Dashboard from "./pages/Dashboard";
import Notifications from "./pages/Notifications";
import QuickActions from "./pages/QuickActions";
import Badges from "./pages/Badges/Badges";
import Rewards from "./pages/Rewards";
import Appreciations from "./pages/Appreciations/Appreciations";
import Profile from "./pages/Profile";
import MetricReports from "./pages/MetricReports";
import QuickActionsContent from "./pages/QuickActionsContent";
import Magazines from "./pages/Magazines";
import Magazine from "./components/Magazines/Magazine";
import MagazineDetails from "./pages/MagazineDetails";
import MessageDetails from "./pages/WallMessages/MessageDetails";
import Messages from "./pages/WallMessages/Messages";
import ApproveRejectFormSubmission from "./pages/ApproveRejectFormSubmission";
import Contests from "./pages/Contests";
import ContestDetails from "./pages/ContestDetails";
import UploadResponse from "./pages/UploadResponse";
import EvaluateDetailingContestResponse from "./pages/EvaluateDetailingContestResponse";
import SendAppreciation from "./pages/Appreciations/SendAppreciation";
import SendAppreciation22 from "./pages/Appreciations/SendAppreciation22";
import CompetitionContests from "./pages/CompetitionContests";
import CompetitionContestDetails from "./pages/CompetitionContestDetails";
import SendBadge from "./pages/Badges/SendBadge";
import SendBadge22 from "./pages/Badges/SendBadge22";
import SendMessage from "./pages/WallMessages/SendMessage";
import SendMessage22 from "./pages/WallMessages/SendMessage22";
import ChangePassword from "./pages/ChangePassword";
//Route Guards
import HomeGuard from "./services/HomeGuard";
import AuthGuard from "./services/AuthGuard";
//React Toastify
import { ToastContainer, Slide } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
//Context
import AppContext from "./AppContext";
import ThemeContext from "./ThemeContext";
//Services
import authService from "./services/Auth";
import notificationServices from "./services/NotificationServices";
//data
import { userProfileData } from "./data/userProfileData";
//Capacitor plugins
import { SplashScreen } from "@capacitor/splash-screen";
import { Device } from "@capacitor/device";
import { DeviceSecurityDetect } from '@capacitor-community/device-security-detect';
//Push Notifications
import { PushNotifications } from "@capacitor/push-notifications";
import { App as CapacitorApp } from "@capacitor/app";
import AppAccessForbidden from "./components/UI/AppAccessForbidden/AppAccessForbidden";
function App() {
SplashScreen.hide();
// console.log("App.jsx loads");
//This below line will stop console logs from printing throughout the app...
// console.log = function () {};
const [isLogin, setIsLogin] = useState(false);
const [theme, setTheme] = useState("light");
const [userProfile, setUserProfile] = useState(userProfileData);
const [backLink, setBackLink] = useState("/");
const [notificationStats, setNotificationStats] = useState(null);
const [showAppAccessForbiddenModal, setShowAppAccessForbiddenModal] =
useState(false);
// App Version Update Confirmation Modal close
const handleCloseAppAccessForbiddenModal = () => {
// console.log("Closing the modal");
setShowAppAccessForbiddenModal(false);
};
//App Version Update Confirmation Modal Open
const handleShowAppAccessForbiddenModal = () => {
setShowAppAccessForbiddenModal(true);
// console.log("Opening the modal");
};
async function closeAppHandler () {
console.log("closeAppHandler called")
await CapacitorApp.exitApp();
}
//Get device info from Capacitor App, Device plugins
const logDeviceInfo = async () => {
// console.log("INSIDE APP.jsx logDeviceInfo()...");
const info = await Device.getInfo();
const deviceID = await Device.getId();
const appInfo = await CapacitorApp.getInfo();
//For Both iOS and Android
// if (info.platform !== "web") {
// console.log("--- Device info = ", JSON.stringify(info));
// console.log("--- Device appInfo = ", JSON.stringify(appInfo));
// console.log("isLogin = ", isLogin);
// console.log("deviceID = ", JSON.stringify(deviceID));
localStorage.setItem("deviceInfo", JSON.stringify(info));
localStorage.setItem("appCurrentVersion", appInfo.version);
localStorage.setItem("appID", appInfo.id);
localStorage.setItem("deviceID", deviceID.identifier);
//Check device OS is Android?
if (info.platform === "android") {
// const { value } = await DeviceSecurityDetect.isJailBreakOrRooted();
async function checkDeviceSecurity() {
console.log("**** checkDeviceSecurity called ***");
try {
const rootStatus = await DeviceSecurityDetect.isJailBreakOrRooted();
// console.log(`*** rootStatus data:`, JSON.stringify(rootStatus));
// console.log(`*** Root/Jailbreak status: ${rootStatus.value ? 'Yes' : 'No'}`);
if(rootStatus.value) {
// handleAlert("Device is ROOTED", "error");
handleShowAppAccessForbiddenModal()
console.log(`*** Device is ROOTED: ${rootStatus.value ? 'Yes' : 'No'}`);
} else {
// handleAlert("Device is not ROOTED and SAFE", "success");
// handleShowAppAccessForbiddenModal()
console.log(`*** Device is NOT ROOTED: ${rootStatus.value ? 'Yes' : 'No'}`);
}
// const pinStatus = await DeviceSecurityDetect.pinCheck();
// console.log(`Secure lock enabled: ${pinStatus.value ? 'Yes' : 'No'}`);
} catch (error) {
console.error('*** Error checking device security:', error);
}
}
checkDeviceSecurity();
}
// }
};
useEffect(() => {
logDeviceInfo();
}, [authService.getToken()]);
useEffect(() => {
const current_theme = localStorage.getItem("theme");
handleThemeChange(current_theme ? current_theme : theme, setTheme);
// let token = localStorage.getItem("auth_token");
let token = authService.getToken();
if (token) {
setIsLogin(true);
}
}, []);
//Apply App state change listener only once...
useEffect(() => {
console.log("refreshToken() and appStateChange listener useEffect");
const listener = CapacitorApp.addListener(
"appStateChange",
({ isActive }) => {
if (isActive) {
console.log("App foregrounded and about to call refreshToken()");
// refreshToken();
}
}
);
// return () => {
// listener.remove();
// };
}, []);
// Get Notification Stats
async function getNotificationStats() {
// console.log("getNotificationStats called from APP.jsx");
notificationServices
.getNotificationStats()
.then((response) => {
if (response.data.status === "success") {
console.log(
"Response from getNotificationsStats on SUCCESS =",
response
);
setNotificationStats(response.data?.data);
}
})
.catch((error) => {
setNotificationStats(null);
console.log("Error in catch in getNotificationsStats =", error);
});
}
//Reverify token
async function reVerifyAuth() {
const token = authService.getToken();
const refToken = authService.getRefreshToken();
if (token && refToken) {
// console.log("Inside if cond / token =", token, "\nrefToken=", refToken);
let data = {
refresh_token: refToken,
};
authService
.reVerifyAuth(data)
.then((response) => {
if (
response.data.status === "success" &&
response.data.statusCode === 200
) {
console.log("Response from REVerifyAuth on SUCCESS =", response);
authService.setToken(response.data.data);
// handleAlert("User revalidated", "success");
} else {
console.log(
"Response from REVerifyAuth on statuscode !== 200 =",
response
);
console.log(
"Invalid session! Please login again...",
response?.data?.message
);
// authService.logout();
localStorage.clear();
handleAlert(response?.data?.message, "error");
setTimeout(() => {
window.location.href = "/";
}, 1500);
}
})
.catch((error) => {
// console.log("Error in catch in reVerifyAuth =", error);
});
}
}
//For getting refreshToken: reverify authetication token on app loads
useEffect(() => {
// reVerifyAuth();
const token = authService.getToken();
if (token) {
console.log(
"...Calling registerDeviceForPushNotification() from App useEffect..."
);
//Notification device and user registration for server
authService.registerDeviceForPushNotification();
//calling to check Local Notifications stats
getNotificationStats();
}
}, []);
/**
* Push Notifications
*/
/** useEffect for Intializing Push notification */
useEffect(() => {
console.log("--**********************--");
console.log("Push notification code useEffect runs...");
console.log("--**********************--");
PushNotifications.checkPermissions().then((res) => {
if (res.receive !== "granted") {
PushNotifications.requestPermissions().then((res) => {
if (res.receive === "denied") {
// showToast("Push Notification permission denied");
console.log("Push Notification permission denied");
} else {
// showToast("Push Notification permission granted");
console.log("Push Notification permission granted");
registerNotifications();
}
});
} else {
console.log(
"if (res.receive !== 'granted') Else Part calling registerNotifications() ",
res?.receive
);
registerNotifications();
}
});
}, []);
async function registerNotifications() {
console.log("--**********************--");
console.log("Initializing HomePage - registerNotifications () called");
console.log("--**********************--");
// Register with Apple / Google to receive push via APNS/FCM
await PushNotifications.register();
// On success, we should be able to receive notifications
await PushNotifications.addListener("registration", (token) => {
console.log(
"PushNotifications.addListener - registration runs Token = ",
token
);
// console.log("Push registration success - Token: ", token);
// console.log("--**********************--");
//Calling below function which will give us current device's info
//storeDeviceAndRegister(token.value);
localStorage.setItem("notificationToken", token.value);
// console.log("--**********************--");
});
// On error, Some issue with our setup and push will not work
await PushNotifications.addListener("registrationError", (error) => {
console.log("PushNotifications.addListener - registrationError runs");
console.log(
"Error on PushNotifications registration: " + JSON.stringify(error)
);
});
// Show us the notification payload if the app is open on our device
// PushNotifications.addListener(
// "pushNotificationReceived",
// (notification) => {
// console.log("PushNotifications.addListener - pushNotificationReceived");
// console.log("notification: ", notification);
// }
// );
// Method called when tapping on a notification
PushNotifications.addListener(
"pushNotificationActionPerformed",
(notification) => {
console.log(
"PushNotifications.addListener - pushNotificationActionPerformed"
);
console.log("Tapped on notification: ", notification);
let user_token = authService.getToken();
// console.log("-- ** user_token = ", user_token);
if (user_token) {
// console.log("--**********************--", user_token);
//Redirecting to notifications if tap on notification...
// window.location.href = `/dashboard/notifications`;
let url = handleNotificationClick(notification?.notification?.data);
window.location.href = url;
// window.location.href = `/dashboard`;
} else {
window.location.href = "/";
}
}
);
}
//Get Device ID and info (i.e. uuid, platform, token, os etc.) of the current device...
async function storeDeviceAndRegister(token) {
console.log("-- ** logDeviceInfo() called... ** --");
const info = await Device.getInfo();
const dev_id = await Device.getId();
const tempData = {
uuid: dev_id.identifier,
platform: info.platform,
package_name: authService.getAppID(),
token: token,
manufacturer: info.manufacturer,
device_model: info.model,
app_version: authService.getAppCurrentVersion(),
version: info.osVersion,
};
console.log("-- tempData = ", tempData);
localStorage.setItem("device_info_notification", tempData);
await authService.registerDeviceForPushNotification(tempData);
console.log("----- Inside logDeviceInfo() -----");
console.log(info);
console.log("--**********************--");
}
return (
<>
<div className="app-wrapper">
<ToastContainer
position="bottom-center"
hideProgressBar={true}
transition={Slide}
theme="dark"
className="custom-toast"
autoClose={3000}
/>
<AppContext.Provider
value={{ userProfile, notificationStats, getNotificationStats, backLink, setBackLink }}
>
<ThemeContext.Provider value={{ theme, setTheme }}>
<BrowserRouter>
<Routes>
{/* <Route path="/" element={<HomeGuest />} /> */}
<Route path="/" element={<HomeGuard component={HomeGuest} />} />
<Route path="/app-icons" element={<AppIcons />} />
<Route
path="/dashboard"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="dashboard"
/>
}
>
<Route index element={<Dashboard />} />
</Route>
<Route
path="/profile"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="profile"
/>
}
>
<Route path="change-password" element={<ChangePassword />} />
<Route index element={<Profile />} />
</Route>
<Route
path="/quick-actions"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="quick-actions"
/>
}
>
<Route index element={<QuickActions />} />
{/* <Route
path="/quick-actions/:id"
element={<QuickActionsContent />}
/> */}
</Route>
<Route
path="/quick-actions-content"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="quick-actions-content"
/>
}
>
<Route index element={<QuickActionsContent />} />
</Route>
<Route
path="/notifications"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="notifications"
/>
}
>
<Route index element={<Notifications />} />
</Route>
<Route
path="/appreciations"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="appreciations"
/>
}
>
<Route
path="send-appreciations2"
element={<SendAppreciation22 />}
/>
<Route
path="send-appreciations"
element={<SendAppreciation />}
/>
<Route index element={<Appreciations />} />
</Route>
<Route
path="/badges"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="badges"
/>
}
>
<Route path="send-badges2" element={<SendBadge22 />} />
<Route path="send-badges" element={<SendBadge />} />
<Route index element={<Badges />} />
</Route>
<Route
path="/rewards"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="rewards"
/>
}
>
<Route index element={<Rewards />} />
</Route>
<Route
path="/metric-reports"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="metric-reports"
/>
}
>
<Route index element={<MetricReports />} />
</Route>
<Route
path="/approve-reject-form-submission"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="approve-reject-form-submission"
/>
}
>
<Route
path=":entityId"
element={<ApproveRejectFormSubmission />}
/>
<Route index element={<ApproveRejectFormSubmission />} />
</Route>
<Route
path="/magazines"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="magazines"
/>
}
>
<Route path=":magazineId" element={<MagazineDetails />} />
<Route index element={<Magazines />} />
</Route>
<Route
path="/messages"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="messages"
/>
}
>
<Route path="send-message2" element={<SendMessage22 />} />
<Route path="send-message" element={<SendMessage />} />
<Route path=":msgId" element={<MessageDetails />} />
<Route index element={<Messages />} />
</Route>
<Route
path="/contests"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="contests"
/>
}
>
<Route path=":contestId" element={<ContestDetails />} />
<Route
path=":contestId/upload-response"
element={<UploadResponse />}
/>
<Route
path=":contestId/evaluate"
element={<EvaluateDetailingContestResponse />}
/>
<Route index element={<Contests />} />
</Route>
<Route
path="/competition-contests"
element={
<AuthGuard
auth={isLogin}
component={DashboardLayout}
page="competition-contests"
/>
}
>
<Route
path="competition-contest-details"
element={<CompetitionContestDetails />}
/>
<Route index element={<CompetitionContests />} />
</Route>
</Routes>
</BrowserRouter>
</ThemeContext.Provider>
</AppContext.Provider>
<AppAccessForbidden
show={showAppAccessForbiddenModal}
// loading={loadingAppInfo}
handleClose={handleCloseAppAccessForbiddenModal}
// platform={authService.getDevicePlatform()}
// appUpdatedInfo={appUpdatedInfo}
closeAppHandler={closeAppHandler}
/>
</div>
</>
);
}
export default App;