Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google analytics functionality for analytics platform #2528

Merged
merged 2 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/platform/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"fuse.js": "^7.0.0",
"html2canvas": "^1.4.1",
"i18n-iso-countries": "^7.7.0",
"js-cookie": "^3.0.5",
"json2csv": "^6.0.0-alpha.2",
"jspdf": "^2.5.2",
"jspdf-autotable": "^3.8.4",
Expand Down
91 changes: 91 additions & 0 deletions src/platform/src/pages/Home/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ import {
import HomeSkeleton from '@/components/skeletons/HomeSkeleton';
import CustomModal from '@/components/Modal/videoModals/CustomModal';
import StepProgress from '@/components/steppers/CircularStepper';
import Cookies from 'js-cookie';
import jwt_decode from 'jwt-decode';
import { useRouter } from 'next/router';
import {
setUserInfo,
setSuccess,
} from '@/lib/store/services/account/LoginSlice';
import { getIndividualUserPreferences } from '@/lib/store/services/account/UserDefaultsSlice';
import { getUserDetails } from '@/core/apis/Account';

const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;

// Video URL constant
const ANALYTICS_VIDEO_URL =
Expand Down Expand Up @@ -60,13 +72,16 @@ const createSteps = (handleModal, handleCardClick) => [

const Home = () => {
const dispatch = useDispatch();
const router = useRouter();

// Selectors
const checkListData = useSelector((state) => state.checklists.checklist);
const cardCheckList = useSelector((state) => state.cardChecklist.cards);
const checkListStatus = useSelector((state) => state.checklists.status);

// State hooks
const [loading, setLoading] = useState(false);

const [open, setOpen] = useState(false);
const [step, setStep] = useState(0);
const totalSteps = 4;
Expand All @@ -85,6 +100,82 @@ const Home = () => {
return null;
}, []);

const retryWithDelay = async (fn, retries = MAX_RETRIES) => {
try {
return await fn();
} catch (error) {
if (retries > 0 && error.response?.status === 429) {
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
return retryWithDelay(fn, retries - 1);
}
throw error;
}
};

// Refactored session setup logic for reuse
const setupUserSession = async (user) => {
if (!user.groups[0]?.grp_title) {
throw new Error(
'Server error. Contact support to add you to the AirQo Organisation',
);
}

localStorage.setItem('loggedUser', JSON.stringify(user));

const preferencesResponse = await retryWithDelay(() =>
dispatch(getIndividualUserPreferences({ identifier: user._id })),
);
if (preferencesResponse.payload.success) {
const preferences = preferencesResponse.payload.preferences;
const activeGroup = preferences[0]?.group_id
? user.groups.find((group) => group._id === preferences[0].group_id)
: user.groups.find((group) => group.grp_title === 'airqo');
localStorage.setItem('activeGroup', JSON.stringify(activeGroup));
}

dispatch(setUserInfo(user));
dispatch(setSuccess(true));
router.push('/Home');
};

// Handle Google redirect
useEffect(() => {
const handleGoogleRedirect = async () => {
if (router.query.success === 'google') {
setLoading(true);
try {
// Retrieve the access_token cookie using js-cookie
const token = Cookies.get('access_token');
if (!token) {
throw new Error('No access_token cookie found');
}

// Store the token in localStorage as 'token'
localStorage.setItem('token', token);
const decoded = jwt_decode(token);

// Fetch user details using the token
const response = await retryWithDelay(() =>
getUserDetails(decoded._id, token),
);
const user = response.users[0];

await setupUserSession(user);
} catch (error) {
dispatch(setSuccess(false));
setLoading(false);
throw error;
}
}
};

handleGoogleRedirect();
}, [router, dispatch]);

if (loading) {
return <HomeSkeleton />;
}

// Handlers
const handleModal = useCallback(() => {
setOpen((prev) => !prev);
Expand Down
24 changes: 24 additions & 0 deletions src/platform/src/pages/account/login/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
} from '@/lib/store/services/account/LoginSlice';
import { getIndividualUserPreferences } from '@/lib/store/services/account/UserDefaultsSlice';
import { postUserLoginDetails, getUserDetails } from '@/core/apis/Account';
import { GOOGLE_AUTH_URL } from '@/core/urls/authentication';

const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;
Expand Down Expand Up @@ -110,6 +111,15 @@ const UserLogin = () => {
dispatch(setUserData({ key, value }));
};

const handleGoogleLogin = async () => {
try {
// Redirect to Google auth URL
window.location.href = GOOGLE_AUTH_URL;
} catch (error) {
console.error('Login error:', error);
}
};

return (
<AccountPageLayout
pageTitle="AirQo Analytics | Login"
Expand Down Expand Up @@ -168,6 +178,7 @@ const UserLogin = () => {
</div>
</div>
</div>

<div className="mt-10">
<button
data-testid="login-btn"
Expand All @@ -181,6 +192,19 @@ const UserLogin = () => {
'Login'
)}
</button>

<button
data-testid="google-login-btn"
className="w-full btn border-blue-900 rounded-[12px] text-white text-sm outline-none border"
disabled={loading}
onClick={handleGoogleLogin}
>
{loading ? (
<Spinner data-testid="spinner" width={25} height={25} />
) : (
'Login with Google'
)}
</button>
</div>
</form>
<div className="mt-8 w-full flex justify-center">
Expand Down
5 changes: 5 additions & 0 deletions src/platform/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5252,6 +5252,11 @@ js-cookie@^2.2.1:
resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-2.2.1.tgz#69e106dc5d5806894562902aa5baec3744e9b2b8"
integrity sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==

js-cookie@^3.0.5:
version "3.0.5"
resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-3.0.5.tgz#0b7e2fd0c01552c58ba86e0841f94dc2557dcdbc"
integrity sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==

"js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
Expand Down
Loading