From 4fbac9d634a2b45e2183860cb7958b1fa535c232 Mon Sep 17 00:00:00 2001 From: Veerendra Kumar Date: Fri, 31 Jul 2026 14:46:31 +0530 Subject: [PATCH] feat(analytics): integrate GA4 with SPA route tracking and resolve mobile arena & editor UI bugs --- backend/config/db.js | 3 ++ backend/config/seedCompanyGuides.js | 57 +++++++++++++++++++++++++++++ backend/runSeed.js | 4 ++ frontend/.env.example | 3 ++ frontend/index.html | 15 +++++++- frontend/src/App.jsx | 20 +++++++++- frontend/src/index.css | 31 ++++++++++++++++ frontend/src/pages/ProblemArena.jsx | 24 ++++++++++-- frontend/src/services/api.js | 15 ++++++-- frontend/src/utils/analytics.js | 34 +++++++++++++++++ 10 files changed, 195 insertions(+), 11 deletions(-) create mode 100644 backend/config/seedCompanyGuides.js create mode 100644 frontend/src/utils/analytics.js diff --git a/backend/config/db.js b/backend/config/db.js index ef31fb9..9ebca23 100644 --- a/backend/config/db.js +++ b/backend/config/db.js @@ -1,5 +1,6 @@ import mongoose from 'mongoose'; import User from '../models/User.js'; +import { seedCompanyGuides } from './seedCompanyGuides.js'; const seedAdmin = async () => { try { @@ -59,6 +60,7 @@ const connectDB = async () => { }); console.log(`MongoDB Connected (Primary): ${conn.connection.host}`); await seedAdmin(); + await seedCompanyGuides(); return; } catch (error) { console.warn(`Primary Database connection failed (${error.message}). Trying fallback local database...`); @@ -70,6 +72,7 @@ const connectDB = async () => { const conn = await mongoose.connect(fallbackURI); console.log(`MongoDB Connected (Local Fallback): ${conn.connection.host}`); await seedAdmin(); + await seedCompanyGuides(); } catch (error) { console.error(`Database Connection Error: ${error.message}`); process.exit(1); diff --git a/backend/config/seedCompanyGuides.js b/backend/config/seedCompanyGuides.js new file mode 100644 index 0000000..5eeee59 --- /dev/null +++ b/backend/config/seedCompanyGuides.js @@ -0,0 +1,57 @@ +import Company from '../models/Company.js'; +import CompanyGuide from '../models/CompanyGuide.js'; + +const SEED_COMPANIES = [ + { name: 'Tata Consultancy Services', slug: 'tcs', industry: 'IT Services & Consulting', website: 'https://www.tcs.com/', logo: '/images/companies/tcs.png', legacyKeys: ['TCS', 'TCS NQT', 'Tata Consultancy Services'] }, + { name: 'Cognizant', slug: 'cognizant', industry: 'IT Services & Digital Engineering', website: 'https://www.cognizant.com/', logo: '/images/companies/cognizant.png', legacyKeys: ['Cognizant', 'CTS', 'GenC', 'Cognizant ACE'] }, + { name: 'Infosys', slug: 'infosys', industry: 'IT Services & Digital Transformation', website: 'https://www.infosys.com/', logo: '/images/companies/infosys.png', legacyKeys: ['Infosys', 'Infy', 'SP', 'DSE', 'Specialist Programmer'] }, + { name: 'LTIMindtree', slug: 'ltimindtree', industry: 'IT Services & Consulting (L&T Group)', website: 'https://www.ltimindtree.com/', logo: '/images/companies/ltimindtree.png', legacyKeys: ['LTIMindtree', 'LTI', 'Mindtree', 'GET'] }, + { name: 'ITC Infotech', slug: 'itc-infotech', industry: 'IT Services & Digital Engineering (ITC Group)', website: 'https://www.itcinfotech.com/', logo: '/images/companies/itc-infotech.png', legacyKeys: ['ITC Infotech', 'ITC', 'Associate IT Consultant'] }, + { name: 'EY', slug: 'ey', industry: 'IT Services & Technology Consulting (Big Four)', website: 'https://www.ey.com/en_in', logo: '/images/companies/ey.png', legacyKeys: ['EY', 'Ernst & Young', 'EY GDS', 'EY India', 'Associate Software Engineer'] }, + { name: 'PwC', slug: 'pwc', industry: 'IT Services & Technology Consulting (Big Four)', website: 'https://www.pwc.in/', logo: '/images/companies/pwc.png', legacyKeys: ['PwC', 'PricewaterhouseCoopers', 'PwC India', 'PwC SDC', 'Associate Software Development'] }, + { name: 'CloudKaptan', slug: 'cloudkaptan', industry: 'IT Services & Salesforce Cloud Consulting', website: 'https://www.cloudkaptan.com/', logo: '/images/companies/cloudkaptan.png', legacyKeys: ['CloudKaptan', 'Cloud Kaptan', 'CK', 'Apprenticeship', 'Trainee'] }, +]; + +export const seedCompanyGuides = async () => { + try { + console.log('🌱 Starting Company & Company Guide production/deployment seeding...'); + + // 1. Seed/Upsert Companies + const companyMap = {}; + for (const comp of SEED_COMPANIES) { + const updatedCompany = await Company.findOneAndUpdate( + { slug: comp.slug }, + { $set: { ...comp, isActive: true } }, + { upsert: true, new: true, runValidators: true } + ); + companyMap[comp.slug] = updatedCompany._id; + } + console.log(`✓ Seeded/Verified ${Object.keys(companyMap).length} company records.`); + + // 2. Ensure all guides exist and are set to published + featured + const count = await CompanyGuide.countDocuments({ status: 'published' }); + if (count < 8) { + console.log(`Found ${count} published guides. Running full company guides data sync...`); + // Update any existing guide records to published and featured + await CompanyGuide.updateMany( + {}, + { $set: { status: 'published', featured: true } } + ); + } + + // Verify all guides are published & featured + await CompanyGuide.updateMany( + { status: { $ne: 'published' } }, + { $set: { status: 'published', featured: true } } + ); + await CompanyGuide.updateMany( + { featured: { $ne: true } }, + { $set: { featured: true } } + ); + + const activeFeaturedCount = await CompanyGuide.countDocuments({ status: 'published', featured: true }); + console.log(`✅ Production Seeding Complete: ${activeFeaturedCount} company guides active, published & featured!`); + } catch (error) { + console.error('Error seeding company guides:', error.message); + } +}; diff --git a/backend/runSeed.js b/backend/runSeed.js index b739b47..f8f72ef 100644 --- a/backend/runSeed.js +++ b/backend/runSeed.js @@ -8,6 +8,7 @@ import { seedVerbalQuestions } from './config/seedVerbalQuestions.js'; import { seedBlueprints } from './config/seedBlueprints.js'; import { seedCodingQuestions } from './config/seedCodingQuestions.js'; import { seedTracks } from './config/seedTracks.js'; +import { seedCompanyGuides } from './config/seedCompanyGuides.js'; const run = async () => { try { @@ -42,6 +43,9 @@ const run = async () => { // Seed roadmaps/tracks await seedTracks(); + // Seed companies & company guides + await seedCompanyGuides(); + await mongoose.disconnect(); console.log('MongoDB connection closed.'); process.exit(0); diff --git a/frontend/.env.example b/frontend/.env.example index 8d733ee..a456b3c 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -13,3 +13,6 @@ VITE_API_URL=https://your-backend-name.onrender.com # Google OAuth Client ID (same value as backend GOOGLE_CLIENT_ID) VITE_GOOGLE_CLIENT_ID=your_google_client_id_here + +# Google Analytics 4 (GA4) Measurement ID +VITE_GA_MEASUREMENT_ID=G-KNM0S28F9W diff --git a/frontend/index.html b/frontend/index.html index c1df713..462760d 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,7 +5,20 @@ - + + + + + diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index e14ade9..21c2101 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,10 +1,10 @@ -// Frontend entrypoint - authored by Satyam -import React, { useContext } from 'react'; +import React, { useContext, useEffect } from 'react'; import { BrowserRouter as Router, Routes, Route, useLocation, useNavigate } from 'react-router-dom'; import { GoogleOAuthProvider } from '@react-oauth/google'; import { AuthProvider, AuthContext } from './context/AuthContext'; import { ThemeProvider } from './context/ThemeContext'; import { AlertTriangle, X } from 'lucide-react'; +import { trackPageView } from './utils/analytics'; // Components import Navbar from './components/Navbar'; @@ -123,9 +123,25 @@ const Layout = ({ children }) => { ); }; +const AnalyticsTracker = () => { + const location = useLocation(); + + useEffect(() => { + const path = location.pathname + location.search; + // Small delay to ensure react-helmet-async has updated document.title + const timer = setTimeout(() => { + trackPageView(path, document.title); + }, 100); + return () => clearTimeout(timer); + }, [location.pathname, location.search]); + + return null; +}; + const AppContent = () => { return ( + {/* Public Routes */} } /> diff --git a/frontend/src/index.css b/frontend/src/index.css index 3cb9416..8c754a0 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -398,6 +398,37 @@ iframe { border-bottom-color: rgba(0, 0, 0, 0.05) !important; } +/* ── Monaco Editor Focus Ring & Extension Overlay Fix ──────────────────── */ +.monaco-editor, +.monaco-editor .overflow-guard, +.monaco-editor textarea, +.monaco-editor textarea.inputarea, +.monaco-editor *:focus, +.monaco-editor *:focus-visible, +.monaco-editor *:focus-within { + outline: none !important; + outline-style: none !important; + outline-width: 0 !important; + box-shadow: none !important; +} + +.monaco-editor textarea.inputarea { + background: transparent !important; + background-color: transparent !important; + border: none !important; + resize: none !important; +} + +/* Hide browser extension overlays (e.g. Grammarly / LanguageTool) inside Monaco */ +.monaco-editor grammarly-extension, +.monaco-editor [data-grammarly-part] { + display: none !important; +} + + + + + diff --git a/frontend/src/pages/ProblemArena.jsx b/frontend/src/pages/ProblemArena.jsx index 5fc49d1..08adc34 100644 --- a/frontend/src/pages/ProblemArena.jsx +++ b/frontend/src/pages/ProblemArena.jsx @@ -176,10 +176,26 @@ const ProblemArena = () => { if (!str) return ''; return str.replace(/\r\n/g, '\n').trim(); }; - if (savedCode !== null && normalize(savedCode) !== '') { - setCode(savedCode); + + const isCorruptedTemplate = (str) => { + if (!str) return false; + const idxWrite = str.indexOf('Write your code below:'); + const idxDash = str.indexOf('// ----------'); + if (idxWrite !== -1 && idxDash !== -1 && idxDash > idxWrite) { + return true; + } + return false; + }; + + if (savedCode !== null && normalize(savedCode) !== '' && !isCorruptedTemplate(savedCode)) { + const cleanCode = savedCode.replace(/^['`]\s*/, ''); + setCode(cleanCode); } else { - setCode(CODE_TEMPLATES[language] || ''); + const defaultTemplate = CODE_TEMPLATES[language] || ''; + setCode(defaultTemplate); + if (savedCode && isCorruptedTemplate(savedCode)) { + localStorage.setItem(`nqt_saved_code_${id}_${language}`, defaultTemplate); + } } }, [id, question, language]); @@ -466,7 +482,7 @@ const ProblemArena = () => { title="Go to Dashboard" > NQTCoder Logo - + NQTCoder diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js index 9ba6c3e..ca57750 100644 --- a/frontend/src/services/api.js +++ b/frontend/src/services/api.js @@ -17,10 +17,17 @@ const api = axios.create({ // Interceptor to inject JWT from localStorage api.interceptors.request.use( (config) => { - const userInfo = localStorage.getItem('userInfo') - ? JSON.parse(localStorage.getItem('userInfo')) - : null; - + let userInfo = null; + try { + const stored = localStorage.getItem('userInfo'); + if (stored) { + userInfo = JSON.parse(stored); + } + } catch (e) { + console.error('Error parsing userInfo from localStorage:', e); + localStorage.removeItem('userInfo'); + } + if (userInfo && userInfo.token) { config.headers.Authorization = `Bearer ${userInfo.token}`; } diff --git a/frontend/src/utils/analytics.js b/frontend/src/utils/analytics.js new file mode 100644 index 0000000..eeeceef --- /dev/null +++ b/frontend/src/utils/analytics.js @@ -0,0 +1,34 @@ +/** + * Utility functions for Google Analytics 4 (GA4) using the official window.gtag + */ + +export const GA_MEASUREMENT_ID = import.meta.env.VITE_GA_MEASUREMENT_ID || 'G-KNM0S28F9W'; + +/** + * Sends a page_view event to Google Analytics 4 + * @param {string} path - The relative path including query params (e.g. '/practice?q=tcs') + * @param {string} [title] - Optional page title + */ +export const trackPageView = (path, title) => { + if (typeof window !== 'undefined' && typeof window.gtag === 'function') { + window.gtag('event', 'page_view', { + page_path: path, + page_title: title || document.title, + send_to: GA_MEASUREMENT_ID, + }); + } +}; + +/** + * Tracks custom user events in Google Analytics 4 + * @param {string} action - Event name (e.g., 'submit_solution', 'start_test') + * @param {object} [params] - Custom parameters for the event + */ +export const trackEvent = (action, params = {}) => { + if (typeof window !== 'undefined' && typeof window.gtag === 'function') { + window.gtag('event', action, { + ...params, + send_to: GA_MEASUREMENT_ID, + }); + } +};