From e634c2d412dff838d315a21c4d82bec5c08ea912 Mon Sep 17 00:00:00 2001 From: Isaiyarasu1909-A Date: Tue, 29 Sep 2026 11:23:16 +0530 Subject: [PATCH 1/2] fix: isolate vitest runner to frontend and remove conflicting @tailwindcss/postcss --- package-lock.json | 595 ---------------------------------------------- package.json | 1 - vite.config.js | 2 +- 3 files changed, 1 insertion(+), 597 deletions(-) diff --git a/package-lock.json b/package-lock.json index 05bbdeb..7664672 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,7 +25,6 @@ }, "devDependencies": { "@eslint/js": "^9.39.1", - "@tailwindcss/postcss": "^4.1.18", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.3.0", @@ -3104,291 +3103,6 @@ "sourcemap-codec": "^1.4.8" } }, - "node_modules/@tailwindcss/node": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz", - "integrity": "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/remapping": "^2.3.4", - "enhanced-resolve": "^5.18.3", - "jiti": "^2.6.1", - "lightningcss": "1.30.2", - "magic-string": "^0.30.21", - "source-map-js": "^1.2.1", - "tailwindcss": "4.1.18" - } - }, - "node_modules/@tailwindcss/node/node_modules/tailwindcss": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz", - "integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tailwindcss/oxide": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.1.18.tgz", - "integrity": "sha512-EgCR5tTS5bUSKQgzeMClT6iCY3ToqE1y+ZB0AKldj809QXk1Y+3jB0upOYZrn9aGIzPtUsP7sX4QQ4XtjBB95A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "optionalDependencies": { - "@tailwindcss/oxide-android-arm64": "4.1.18", - "@tailwindcss/oxide-darwin-arm64": "4.1.18", - "@tailwindcss/oxide-darwin-x64": "4.1.18", - "@tailwindcss/oxide-freebsd-x64": "4.1.18", - "@tailwindcss/oxide-linux-arm-gnueabihf": "4.1.18", - "@tailwindcss/oxide-linux-arm64-gnu": "4.1.18", - "@tailwindcss/oxide-linux-arm64-musl": "4.1.18", - "@tailwindcss/oxide-linux-x64-gnu": "4.1.18", - "@tailwindcss/oxide-linux-x64-musl": "4.1.18", - "@tailwindcss/oxide-wasm32-wasi": "4.1.18", - "@tailwindcss/oxide-win32-arm64-msvc": "4.1.18", - "@tailwindcss/oxide-win32-x64-msvc": "4.1.18" - } - }, - "node_modules/@tailwindcss/oxide-android-arm64": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.1.18.tgz", - "integrity": "sha512-dJHz7+Ugr9U/diKJA0W6N/6/cjI+ZTAoxPf9Iz9BFRF2GzEX8IvXxFIi/dZBloVJX/MZGvRuFA9rqwdiIEZQ0Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-darwin-arm64": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.1.18.tgz", - "integrity": "sha512-Gc2q4Qhs660bhjyBSKgq6BYvwDz4G+BuyJ5H1xfhmDR3D8HnHCmT/BSkvSL0vQLy/nkMLY20PQ2OoYMO15Jd0A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-darwin-x64": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.1.18.tgz", - "integrity": "sha512-FL5oxr2xQsFrc3X9o1fjHKBYBMD1QZNyc1Xzw/h5Qu4XnEBi3dZn96HcHm41c/euGV+GRiXFfh2hUCyKi/e+yw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-freebsd-x64": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.1.18.tgz", - "integrity": "sha512-Fj+RHgu5bDodmV1dM9yAxlfJwkkWvLiRjbhuO2LEtwtlYlBgiAT4x/j5wQr1tC3SANAgD+0YcmWVrj8R9trVMA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.1.18.tgz", - "integrity": "sha512-Fp+Wzk/Ws4dZn+LV2Nqx3IilnhH51YZoRaYHQsVq3RQvEl+71VGKFpkfHrLM/Li+kt5c0DJe/bHXK1eHgDmdiA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.1.18.tgz", - "integrity": "sha512-S0n3jboLysNbh55Vrt7pk9wgpyTTPD0fdQeh7wQfMqLPM/Hrxi+dVsLsPrycQjGKEQk85Kgbx+6+QnYNiHalnw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-musl": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.1.18.tgz", - "integrity": "sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-gnu": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.1.18.tgz", - "integrity": "sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-musl": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.1.18.tgz", - "integrity": "sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.1.18.tgz", - "integrity": "sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==", - "bundleDependencies": [ - "@napi-rs/wasm-runtime", - "@emnapi/core", - "@emnapi/runtime", - "@tybys/wasm-util", - "@emnapi/wasi-threads", - "tslib" - ], - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1", - "@emnapi/wasi-threads": "^1.1.0", - "@napi-rs/wasm-runtime": "^1.1.0", - "@tybys/wasm-util": "^0.10.1", - "tslib": "^2.4.0" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.18.tgz", - "integrity": "sha512-HjSA7mr9HmC8fu6bdsZvZ+dhjyGCLdotjVOgLA2vEqxEBZaQo9YTX4kwgEvPCpRh8o4uWc4J/wEoFzhEmjvPbA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/oxide-win32-x64-msvc": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.1.18.tgz", - "integrity": "sha512-bJWbyYpUlqamC8dpR7pfjA0I7vdF6t5VpUGMWRkXVE3AXgIZjYUYAK7II1GNaxR8J1SSrSrppRar8G++JekE3Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tailwindcss/postcss": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.1.18.tgz", - "integrity": "sha512-Ce0GFnzAOuPyfV5SxjXGn0CubwGcuDB0zcdaPuCSzAa/2vII24JTkH+I6jcbXLb1ctjZMZZI6OjDaLPJQL1S0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@alloc/quick-lru": "^5.2.0", - "@tailwindcss/node": "4.1.18", - "@tailwindcss/oxide": "4.1.18", - "postcss": "^8.4.41", - "tailwindcss": "4.1.18" - } - }, - "node_modules/@tailwindcss/postcss/node_modules/tailwindcss": { - "version": "4.1.18", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz", - "integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==", - "dev": true, - "license": "MIT" - }, "node_modules/@testing-library/dom": { "version": "10.4.1", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", @@ -4955,16 +4669,6 @@ "node": ">=6" } }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, "node_modules/didyoumean": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", @@ -5060,20 +4764,6 @@ "node": ">=10.0.0" } }, - "node_modules/enhanced-resolve": { - "version": "5.18.4", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.4.tgz", - "integrity": "sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.4", - "tapable": "^2.2.0" - }, - "engines": { - "node": ">=10.13.0" - } - }, "node_modules/entities": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", @@ -6889,16 +6579,6 @@ "node": ">=10" } }, - "node_modules/jiti": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", - "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", - "dev": true, - "license": "MIT", - "bin": { - "jiti": "lib/jiti-cli.mjs" - } - }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -7112,267 +6792,6 @@ "node": ">= 0.8.0" } }, - "node_modules/lightningcss": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz", - "integrity": "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.30.2", - "lightningcss-darwin-arm64": "1.30.2", - "lightningcss-darwin-x64": "1.30.2", - "lightningcss-freebsd-x64": "1.30.2", - "lightningcss-linux-arm-gnueabihf": "1.30.2", - "lightningcss-linux-arm64-gnu": "1.30.2", - "lightningcss-linux-arm64-musl": "1.30.2", - "lightningcss-linux-x64-gnu": "1.30.2", - "lightningcss-linux-x64-musl": "1.30.2", - "lightningcss-win32-arm64-msvc": "1.30.2", - "lightningcss-win32-x64-msvc": "1.30.2" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.30.2.tgz", - "integrity": "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.30.2.tgz", - "integrity": "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.30.2.tgz", - "integrity": "sha512-oBZgKchomuDYxr7ilwLcyms6BCyLn0z8J0+ZZmfpjwg9fRVZIR5/GMXd7r9RH94iDhld3UmSjBM6nXWM2TfZTQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.30.2.tgz", - "integrity": "sha512-c2bH6xTrf4BDpK8MoGG4Bd6zAMZDAXS569UxCAGcA7IKbHNMlhGQ89eRmvpIUGfKWNVdbhSbkQaWhEoMGmGslA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.30.2.tgz", - "integrity": "sha512-eVdpxh4wYcm0PofJIZVuYuLiqBIakQ9uFZmipf6LF/HRj5Bgm0eb3qL/mr1smyXIS1twwOxNWndd8z0E374hiA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.30.2.tgz", - "integrity": "sha512-UK65WJAbwIJbiBFXpxrbTNArtfuznvxAJw4Q2ZGlU8kPeDIWEX1dg3rn2veBVUylA2Ezg89ktszWbaQnxD/e3A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.30.2.tgz", - "integrity": "sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.30.2.tgz", - "integrity": "sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.30.2.tgz", - "integrity": "sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.30.2.tgz", - "integrity": "sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.30.2", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.30.2.tgz", - "integrity": "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, "node_modules/lilconfig": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", @@ -9518,20 +8937,6 @@ "jiti": "bin/jiti.js" } }, - "node_modules/tapable": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz", - "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, "node_modules/temp-dir": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz", diff --git a/package.json b/package.json index 7b880d9..5f3a356 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,6 @@ }, "devDependencies": { "@eslint/js": "^9.39.1", - "@tailwindcss/postcss": "^4.1.18", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.3.0", diff --git a/vite.config.js b/vite.config.js index 43fd531..01b646f 100644 --- a/vite.config.js +++ b/vite.config.js @@ -25,6 +25,7 @@ export default defineConfig({ environment: 'jsdom', setupFiles: ['./src/__tests__/setup.js'], css: true, + include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], coverage: { provider: 'v8', reporter: ['text', 'json', 'html'], @@ -32,4 +33,3 @@ export default defineConfig({ }, }, }); - From d80afcc7c65a09edbb384029879ace7b884e61c2 Mon Sep 17 00:00:00 2001 From: Isaiyarasu1909-A Date: Tue, 29 Sep 2026 11:23:48 +0530 Subject: [PATCH 2/2] fix: resolve ESLint warnings and enforce clean Prettier formatting for CI --- .gitattributes | 4 + .prettierrc | 2 +- BLOG.md | 34 +- PROJECT_DESCRIPTION.md | 59 +- README.md | 73 +- README_PRODUCTION.md | 5 + eslint.config.js | 11 +- index.html | 51 +- postcss.config.js | 10 +- server/config/adminSecret.js | 18 +- server/config/jwt.js | 28 +- server/index.js | 78 +- server/middleware/admin.js | 10 +- server/middleware/auth.js | 28 +- server/models/Booking.js | 242 ++- server/models/User.js | 254 +-- server/package.json | 12 +- server/routes/auth.js | 95 +- server/routes/bookings.js | 490 ++--- server/routes/payments.js | 88 +- server/routes/rapidsAnalytics.js | 274 +-- server/routes/webhooks.js | 50 +- server/utils/SimulationService.js | 64 +- server/utils/jsonDB.js | 167 +- src/App.jsx | 94 +- src/__tests__/ParkingCard.test.jsx | 9 +- src/components/ThemeContext.jsx | 34 +- src/components/layout/DashboardLayout.jsx | 54 +- src/components/layout/Header.jsx | 109 +- src/components/layout/Sidebar.jsx | 326 +-- .../notifications/NotificationSystem.jsx | 263 +-- src/components/parking/BookingHistory.jsx | 473 +++-- src/components/parking/BookingModal.jsx | 659 +++--- src/components/parking/QRCodeGenerator.jsx | 122 +- src/components/parking/RouteOptimizer.jsx | 377 ++-- src/components/parking/SlotGrid.jsx | 135 +- src/components/payment/PaymentModal.jsx | 1117 +++++----- src/components/traffic/IntersectionMap.jsx | 291 +-- src/components/traffic/LiveCityMap.jsx | 388 ++-- src/components/traffic/SignalControl.jsx | 72 +- src/context/AppContext.jsx | 44 +- src/hooks/useIoT.js | 38 +- src/hooks/usePWA.js | 92 +- src/index.css | 2 +- src/main.jsx | 8 +- src/pages/AcceleratedAnalytics.jsx | 1793 +++++++++-------- src/pages/AdminUsers.jsx | 201 +- src/pages/Analytics.jsx | 412 ++-- src/pages/CitizenPortal.jsx | 103 +- src/pages/Dashboard.jsx | 421 ++-- src/pages/ParkingAnalytics.jsx | 564 +++--- src/pages/ParkingDashboard.jsx | 1761 ++++++++-------- src/pages/Settings.jsx | 310 +-- src/pages/TrafficCV.jsx | 76 +- src/pages/TrafficDashboard.jsx | 1075 +++++----- src/pages/auth/Login.jsx | 233 +-- src/pages/auth/Register.jsx | 403 ++-- src/services/api.js | 320 +-- tailwind.config.js | 75 +- 59 files changed, 7985 insertions(+), 6616 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d2e4fd8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# Set default behavior to automatically normalize line endings +* text=auto eol=lf +*.bat eol=crlf +*.cmd eol=crlf diff --git a/.prettierrc b/.prettierrc index a6d7575..8471d0b 100644 --- a/.prettierrc +++ b/.prettierrc @@ -9,5 +9,5 @@ "bracketSpacing": true, "bracketSameLine": false, "arrowParens": "always", - "endOfLine": "lf" + "endOfLine": "auto" } diff --git a/BLOG.md b/BLOG.md index 0342560..2a57824 100644 --- a/BLOG.md +++ b/BLOG.md @@ -1,10 +1,10 @@ # Say Goodbye to Gridlocks: How TraffiTech is Automating Smart Cities with AI and IoT -We’ve all been there: stuck at a red light on an entirely empty intersection, or circling the block for the fifth time just looking for a place to park. +We’ve all been there: stuck at a red light on an entirely empty intersection, or circling the block for the fifth time just looking for a place to park. -In modern cities, traffic and parking systems operate as isolated silos. Static traffic light timers don’t care about actual road density, and drivers looking for parking space search passively, contributing to **up to 30% of urban congestion**. Most critically, emergency vehicles like ambulances face life-threatening delays navigating gridlocked intersections. +In modern cities, traffic and parking systems operate as isolated silos. Static traffic light timers don’t care about actual road density, and drivers looking for parking space search passively, contributing to **up to 30% of urban congestion**. Most critically, emergency vehicles like ambulances face life-threatening delays navigating gridlocked intersections. -To solve this, I built **TraffiTech**—an AI-powered, IoT-integrated cyber-physical system designed to optimize large-scale traffic control and parking allocation in real-time. +To solve this, I built **TraffiTech**—an AI-powered, IoT-integrated cyber-physical system designed to optimize large-scale traffic control and parking allocation in real-time. Here is a deep dive into how TraffiTech works, the technical engine under the hood, and how it's shaping the future of smart city infrastructure. @@ -19,31 +19,36 @@ Instead of separating navigation and parking, TraffiTech unites them into a sing Here are the key pillars that make TraffiTech unique: ### 1. AI-Powered Traffic Autopilot -Traditional traffic lights run on pre-programmed cycles. TraffiTech uses virtual IoT road sensors to continuously stream vehicle density counts. The system’s **AI Autopilot** evaluates these density thresholds in real-time and dynamically extends green-light cycles for heavily congested lanes while shortening green phases for empty corridors. + +Traditional traffic lights run on pre-programmed cycles. TraffiTech uses virtual IoT road sensors to continuously stream vehicle density counts. The system’s **AI Autopilot** evaluates these density thresholds in real-time and dynamically extends green-light cycles for heavily congested lanes while shortening green phases for empty corridors. ### 2. Life-Saving SOS Corridors + Every second counts during a medical or fire emergency. TraffiTech features a manual **Emergency Corridor Override**. With a single click, dispatchers or first responders can force a continuous green-light pathway along the emergency vehicle's route, proactively clearing traffic gridlocks before the vehicle even arrives at the intersection. ### 3. Contactless Smart Parking & Dynamic Pricing + Drivers can open the TraffiTech mobile app to locate vacant parking spots on an interactive, geolocation-aware map. To balance parking gridlocks during peak hours, the system automatically triggers dynamic surge pricing. Once a spot is selected, users book it securely using Stripe and receive a digital QR ticket. Scanning this QR pass at the physical gate updates the live database occupancy immediately. ### 4. Eco-Smart Infrastructure (Smart Streetlighting) + To reduce municipal energy costs, TraffiTech links density sensors to streetlighting networks. During off-peak night hours, streetlights automatically dim by up to 50% when the road is empty and instantly return to 100% brightness as vehicles approach, reducing grid loads by up to 40%. --- ## Under the Hood: The Tech Stack -Building a real-time smart city dashboard requires high performance, security, and absolute reliability. +Building a real-time smart city dashboard requires high performance, security, and absolute reliability. -* **Frontend:** Built as a Progressive Web Application (PWA) using **React 19** and **Vite** for rapid rendering. **Tailwind CSS** handles the styling, **Leaflet** powers the interactive maps, and **Recharts** handles live analytics. -* **Backend:** Powered by **Node.js** and **Express.js**. I used **Socket.io** to establish persistent, bi-directional WebSocket streams to handle the real-time IoT signal cycles. -* **Payments:** Elements from the **Stripe API** are fully integrated to handle secure, PCI-compliant bookings. +- **Frontend:** Built as a Progressive Web Application (PWA) using **React 19** and **Vite** for rapid rendering. **Tailwind CSS** handles the styling, **Leaflet** powers the interactive maps, and **Recharts** handles live analytics. +- **Backend:** Powered by **Node.js** and **Express.js**. I used **Socket.io** to establish persistent, bi-directional WebSocket streams to handle the real-time IoT signal cycles. +- **Payments:** Elements from the **Stripe API** are fully integrated to handle secure, PCI-compliant bookings. ![TraffiTech Live Dashboard](https://raw.githubusercontent.com/10-Mohan/Trafitech/main/documentation/assets/real_dashboard.png) ### Engineering for Offline Resilience -Critical city infrastructure cannot afford downtime. If the internet drops, traffic lights must keep running. + +Critical city infrastructure cannot afford downtime. If the internet drops, traffic lights must keep running. To solve this, I engineered a **hybrid database storage engine**. While the production system runs on **MongoDB Atlas** in the cloud, the database adapter automatically detects connection drops and fails over to a zero-dependency **local JSON database fallback**. This ensures that local servers can keep processing data offline until connectivity is restored. @@ -52,12 +57,13 @@ To solve this, I engineered a **hybrid database storage engine**. While the prod ## The Road Ahead TraffiTech is a foundation. The next steps in our roadmap focus on large-scale logistics: -* **Freight Priority Routing:** Integrating with registered delivery fleets to coordinate "Priority Green" windows, optimizing industrial supply chains. -* **Urban Planning Simulator:** A sandbox mode for city engineers to test new road layouts (like roundabouts) against historical traffic data before investing physical capital. + +- **Freight Priority Routing:** Integrating with registered delivery fleets to coordinate "Priority Green" windows, optimizing industrial supply chains. +- **Urban Planning Simulator:** A sandbox mode for city engineers to test new road layouts (like roundabouts) against historical traffic data before investing physical capital. Smart cities shouldn't just passively observe congestion—they should actively clear it. With AI, IoT, and resilient architectures, platforms like TraffiTech are paving the way for safer, cleaner, and highly coordinated urban transit. -*** +--- -* 👉 [TraffiTech Live Demo](https://trafitech-git-main-10-mohans-projects.vercel.app/) -* 👉 [Explore the Code on GitHub](https://github.com/10-Mohan/Trafitech) +- 👉 [TraffiTech Live Demo](https://trafitech-git-main-10-mohans-projects.vercel.app/) +- 👉 [Explore the Code on GitHub](https://github.com/10-Mohan/Trafitech) diff --git a/PROJECT_DESCRIPTION.md b/PROJECT_DESCRIPTION.md index d679086..568c8b5 100644 --- a/PROJECT_DESCRIPTION.md +++ b/PROJECT_DESCRIPTION.md @@ -1,17 +1,21 @@ # 🏙️ TraffiTech: Smart Traffic & Parking Management System -### *End-to-End Project Description & Technical Documentation* + +### _End-to-End Project Description & Technical Documentation_ --- ## 📌 Executive Summary -**TraffiTech** is a Progressive Web Application (PWA) designed to address two of the most critical challenges facing modern urban areas: **traffic congestion** and **inefficient parking space allocation**. + +**TraffiTech** is a Progressive Web Application (PWA) designed to address two of the most critical challenges facing modern urban areas: **traffic congestion** and **inefficient parking space allocation**. By combining real-time IoT sensor telemetry, interactive map visualizations (React-Leaflet), automated Stripe payment processing, and dynamic demand-based pricing, TraffiTech creates a unified ecosystem for citizens and city administrators. It streamlines the parking space discovery process, dynamically controls traffic light cycles based on vehicle density, and provides critical safety features like real-time emergency routing overrides. --- ## ⚠️ The Problem Statement + As urban populations grow, legacy traffic control and parking infrastructures fail to scale: + 1. **Inefficient Parking Search:** Studies show that drivers searching for parking account for up to **30% of urban traffic congestion**, resulting in wasted fuel, higher carbon emissions, and driver frustration. 2. **Static Traffic Signal Timing:** Conventional traffic lights operate on fixed, pre-programmed timers that do not adjust to actual traffic flow, leading to unnecessary idling and gridlocks during peak hours. 3. **Emergency Vehicle Delays:** First responders (ambulances, fire engines) face critical delays navigating gridlocked intersections, which can directly affect patient survival rates. @@ -20,6 +24,7 @@ As urban populations grow, legacy traffic control and parking infrastructures fa --- ## 💡 The Solution: TraffiTech + TraffiTech bridges these silos by integrating real-time traffic signal automation and reservation-based parking into a single, responsive platform. ```mermaid @@ -41,32 +46,36 @@ graph TD ## 🛠️ Core Features & Detailed Workflows ### 🚦 1. Adaptive Traffic Control Center -* **Emergency Corridor Override (SOS):** Allows dispatcher networks or EMT responders to trigger a global emergency override. The system immediately forces the required vertical or horizontal route into a continuous green light sequence, clearing traffic blocks before the vehicle arrives. -* **AI-Powered Autopilot Mode:** Evaluates live density readings from simulated IoT sensors and dynamically adjusts cycle durations. Lanes with high vehicle density are prioritized, while empty corridors receive shorter green windows, keeping traffic flowing continuously. -* **Live Simulation Map:** An interactive, responsive crossroads schematic mapping active signals, current speeds, and active vehicle counters. + +- **Emergency Corridor Override (SOS):** Allows dispatcher networks or EMT responders to trigger a global emergency override. The system immediately forces the required vertical or horizontal route into a continuous green light sequence, clearing traffic blocks before the vehicle arrives. +- **AI-Powered Autopilot Mode:** Evaluates live density readings from simulated IoT sensors and dynamically adjusts cycle durations. Lanes with high vehicle density are prioritized, while empty corridors receive shorter green windows, keeping traffic flowing continuously. +- **Live Simulation Map:** An interactive, responsive crossroads schematic mapping active signals, current speeds, and active vehicle counters. ### 🅿️ 2. Smart Parking Space Allocation -* **Interactive Geolocation Spotting:** Integrates React-Leaflet maps to automatically capture the user's GPS coordinates and display nearby parking garages. -* **Dynamic Surge Pricing:** Features demand-responsive pricing logic. During peak hours (9:00–11:00 AM & 5:00–7:00 PM), the hourly parking rate scales by **1.5x** automatically to manage parking gridlocks. -* **Seamless Reservation Flow:** Built with Stripe Elements. Users securely enter checkout credentials, receive automated session confirmations, and generate a dynamic, digital **QR Access Ticket** for contactless gate verification. + +- **Interactive Geolocation Spotting:** Integrates React-Leaflet maps to automatically capture the user's GPS coordinates and display nearby parking garages. +- **Dynamic Surge Pricing:** Features demand-responsive pricing logic. During peak hours (9:00–11:00 AM & 5:00–7:00 PM), the hourly parking rate scales by **1.5x** automatically to manage parking gridlocks. +- **Seamless Reservation Flow:** Built with Stripe Elements. Users securely enter checkout credentials, receive automated session confirmations, and generate a dynamic, digital **QR Access Ticket** for contactless gate verification. ### 📊 3. Executive Data Insights -* **System Analytics:** Features custom-styled **Recharts** line charts showing traffic volume trends mapped against hourly parking occupancy over 24 hours. -* **Revenue & Space Management:** Displays cumulative revenue, total transactions, and fills/availabilities per parking zone (Week, Month, Year views). + +- **System Analytics:** Features custom-styled **Recharts** line charts showing traffic volume trends mapped against hourly parking occupancy over 24 hours. +- **Revenue & Space Management:** Displays cumulative revenue, total transactions, and fills/availabilities per parking zone (Week, Month, Year views). --- ## 💻 Tech Stack & Architecture -* **Frontend (Single Page App):** React 19, Vite, Tailwind CSS, Leaflet, Recharts, Lucide Icons, Framer Motion. -* **Backend (REST API & WebSockets):** Node.js, Express, Socket.io (for streaming real-time IoT signal cycles). -* **Database (Hybrid Storage Model):** MongoDB Atlas (Cloud database) backed by a Zero-Dependency local JSON file database fallback for maximum reliability. -* **Payment Gateway:** Stripe API integration. -* **Hosting & Production:** Frontend hosted on **Vercel**, Backend hosted on **Render** (fully hosted in the cloud, running 24/7). +- **Frontend (Single Page App):** React 19, Vite, Tailwind CSS, Leaflet, Recharts, Lucide Icons, Framer Motion. +- **Backend (REST API & WebSockets):** Node.js, Express, Socket.io (for streaming real-time IoT signal cycles). +- **Database (Hybrid Storage Model):** MongoDB Atlas (Cloud database) backed by a Zero-Dependency local JSON file database fallback for maximum reliability. +- **Payment Gateway:** Stripe API integration. +- **Hosting & Production:** Frontend hosted on **Vercel**, Backend hosted on **Render** (fully hosted in the cloud, running 24/7). --- ## 🌟 Why TraffiTech is Different + 1. **Unified Ecosystem:** Instead of using separate apps for traffic navigation and parking booking, TraffiTech joins them together to help drivers park before hitting gridlocks. 2. **Offline Resilience:** The application's database adapter automatically fails over to local files if cloud servers are unreachable, guaranteeing zero downtime. 3. **Progressive Web App (PWA) First:** Fully installable directly onto mobile home screens without requiring native app store downloads. @@ -74,22 +83,24 @@ graph TD --- ## 📈 Future Scope & Large-Scale Optimizations + Based on the physical and digital systems optimization domain, we have designed a roadmap detailing three large-scale features: 1. **🚚 Freight & Logistics Priority Routing (Supply Chain)** - * **Concept:** Integration with registered delivery truck fleets (e.g., Amazon, FedEx). The system recognizes these logistics vehicles on approaching corridors and coordinates the traffic grid to provide "Priority Green" windows. - * **Impact:** Drastically reduces delivery delay overhead, lowers idling fuel waste, and optimizes supply chain flow inside heavy commercial zones. - + - **Concept:** Integration with registered delivery truck fleets (e.g., Amazon, FedEx). The system recognizes these logistics vehicles on approaching corridors and coordinates the traffic grid to provide "Priority Green" windows. + - **Impact:** Drastically reduces delivery delay overhead, lowers idling fuel waste, and optimizes supply chain flow inside heavy commercial zones. + 2. **💡 IoT-Based Smart Streetlighting (Infrastructure Energy Management)** - * **Concept:** Linking physical city streetlighting grids directly to TraffiTech's traffic density sensors. When zero traffic is detected during off-peak night hours, streetlights dim by 50% automatically and ramp back to 100% brightness as vehicles approach. - * **Impact:** Slashes city energy costs and grid loads by up to 40% while keeping roads safely lit. + - **Concept:** Linking physical city streetlighting grids directly to TraffiTech's traffic density sensors. When zero traffic is detected during off-peak night hours, streetlights dim by 50% automatically and ramp back to 100% brightness as vehicles approach. + - **Impact:** Slashes city energy costs and grid loads by up to 40% while keeping roads safely lit. 3. **📐 Urban Planning Simulator (Virtual Layout Builder)** - * **Concept:** A sandbox simulation mode built into the admin control panel. It allows traffic engineers to test route redesigns (e.g., adding roundabouts or modifying parking garages) against historical volume trends. - * **Impact:** Enables predictive urban planning before spending capital resources on physical roadway redesign. + - **Concept:** A sandbox simulation mode built into the admin control panel. It allows traffic engineers to test route redesigns (e.g., adding roundabouts or modifying parking garages) against historical volume trends. + - **Impact:** Enables predictive urban planning before spending capital resources on physical roadway redesign. --- ## 🚀 Live Access Links -* **Live Application URL:** [https://trafitech-git-main-10-mohans-projects.vercel.app/](https://trafitech-git-main-10-mohans-projects.vercel.app/) -* **GitHub Code Repository:** [https://github.com/10-Mohan/Trafitech](https://github.com/10-Mohan/Trafitech) + +- **Live Application URL:** [https://trafitech-git-main-10-mohans-projects.vercel.app/](https://trafitech-git-main-10-mohans-projects.vercel.app/) +- **GitHub Code Repository:** [https://github.com/10-Mohan/Trafitech](https://github.com/10-Mohan/Trafitech) diff --git a/README.md b/README.md index c98917b..1a0cdad 100644 --- a/README.md +++ b/README.md @@ -16,23 +16,27 @@ TraffiTech is an end-to-end, AI-powered Progressive Web Application (PWA) design ## 🎯 Key Features ### 🚥 1. Traffic Control Center -* **Active Corridor Preemption:** One-click emergency corridor override to clear lanes for EMTs/ambulances. -* **Auto-Pilot Mode:** AI-driven cycle recommendations that adjust traffic light durations dynamically based on vehicle density. -* **Live Intersection Map:** Interactive SVG visualization of road intersections with active car flow animations. + +- **Active Corridor Preemption:** One-click emergency corridor override to clear lanes for EMTs/ambulances. +- **Auto-Pilot Mode:** AI-driven cycle recommendations that adjust traffic light durations dynamically based on vehicle density. +- **Live Intersection Map:** Interactive SVG visualization of road intersections with active car flow animations. ### 🚗 2. Smart Parking Allocation -* **Interactive Geolocation Map:** Real-time user localization with automatic discovery of nearby parking zones via Leaflet. -* **Dynamic Surge Pricing:** Automatic price adjustments (1.5x multiplier) during high-demand peak hours. -* **Integrated Booking & Payments:** Secure reservation of selected slots backed by Stripe API test payments. -* **Digital Access Tickets:** Generates dynamic, secure QR codes for automated entry and exit authentication. + +- **Interactive Geolocation Map:** Real-time user localization with automatic discovery of nearby parking zones via Leaflet. +- **Dynamic Surge Pricing:** Automatic price adjustments (1.5x multiplier) during high-demand peak hours. +- **Integrated Booking & Payments:** Secure reservation of selected slots backed by Stripe API test payments. +- **Digital Access Tickets:** Generates dynamic, secure QR codes for automated entry and exit authentication. ### 📊 3. Executive Analytics Dashboards -* **System Analytics:** Interactive Recharts trendlines measuring traffic density vs. parking availability over 24 hours. -* **Parking Analytics:** Real-time occupancy breakdown (Available, Occupied, Reserved) and revenue projections categorized by date ranges (week, month, year). + +- **System Analytics:** Interactive Recharts trendlines measuring traffic density vs. parking availability over 24 hours. +- **Parking Analytics:** Real-time occupancy breakdown (Available, Occupied, Reserved) and revenue projections categorized by date ranges (week, month, year). ### 📱 4. Progressive Web App (PWA) Support -* Fully responsive UI optimized for mobile viewports, landscape tablets, and desktop setups. -* Offline capability and quick launch access via home screen installation. + +- Fully responsive UI optimized for mobile viewports, landscape tablets, and desktop setups. +- Offline capability and quick launch access via home screen installation. --- @@ -53,10 +57,12 @@ graph TD ## 💻 Local Setup & Development ### Prerequisites -* [Node.js](https://nodejs.org/) (v16+) -* npm (v8+) + +- [Node.js](https://nodejs.org/) (v16+) +- npm (v8+) ### 1. Clone & Install Dependencies + ```bash # Clone the repository git clone https://github.com/10-Mohan/Trafitech.git @@ -71,7 +77,9 @@ npm install ``` ### 2. Configure Environment Variables + Create a `.env` file inside the `server/` directory: + ```env PORT=5000 MONGODB_URI=mongodb://localhost:27017/traffitech @@ -82,6 +90,7 @@ STRIPE_SECRET_KEY=your_stripe_sk_test_key ``` ### 3. Run Locally + ```bash # Start the Backend Server (from server/ directory) npm run dev @@ -89,10 +98,13 @@ npm run dev # Start the Frontend Vite Client (from root directory in a new terminal) npm run dev ``` + ### 🔑 Account Registration & Admin Passcode + When creating a new account on the registration page: -* **Driver Account:** Select **"Regular Driver"**, enter your email, username, and password. -* **City Admin Account:** Select **"City Admin"**, enter your details, and provide the **Admin Security Passcode**: + +- **Driver Account:** Select **"Regular Driver"**, enter your email, username, and password. +- **City Admin Account:** Select **"City Admin"**, enter your details, and provide the **Admin Security Passcode**: ```text traffitech-admin-2026 ``` @@ -104,26 +116,31 @@ When creating a new account on the registration page: The project is fully set up for 24/7 cloud availability without requiring your local laptop to run: ### 1. Database (MongoDB Atlas) -* Spin up a free cluster on MongoDB Atlas. -* Set IP Access list to `0.0.0.0/0` (Allow access from anywhere). -* Copy your connection string and insert your user credentials. + +- Spin up a free cluster on MongoDB Atlas. +- Set IP Access list to `0.0.0.0/0` (Allow access from anywhere). +- Copy your connection string and insert your user credentials. ### 2. Backend (Render.com) -* Create a new Web Service pointing to your repository. -* Set the Root Directory to `server`. -* Set Build Command to `npm install` and Start Command to `node index.js`. -* Input your `MONGODB_URI`, `JWT_SECRET`, and Stripe keys as environment variables. + +- Create a new Web Service pointing to your repository. +- Set the Root Directory to `server`. +- Set Build Command to `npm install` and Start Command to `node index.js`. +- Input your `MONGODB_URI`, `JWT_SECRET`, and Stripe keys as environment variables. ### 3. Frontend (Vercel.com) -* Connect your repository to Vercel. -* Set the Build Command to `npm run build` and Output Directory to `dist`. -* Add `VITE_API_URL` pointing to your Render service (`https://your-api.onrender.com/api`). -* Vercel will automatically trigger deployments on every git push to your `main` branch. + +- Connect your repository to Vercel. +- Set the Build Command to `npm run build` and Output Directory to `dist`. +- Add `VITE_API_URL` pointing to your Render service (`https://your-api.onrender.com/api`). +- Vercel will automatically trigger deployments on every git push to your `main` branch. --- ### 🔑 Account Registration & Admin Passcode + When creating a new account on the registration page: -* **Driver Account:** Select **"Regular Driver"**, enter your email, username, and password. -* **City Admin Account:** Select **"City Admin"**, enter your details, and provide the **Admin Security Passcode**: + +- **Driver Account:** Select **"Regular Driver"**, enter your email, username, and password. +- **City Admin Account:** Select **"City Admin"**, enter your details, and provide the **Admin Security Passcode**: `traffitech-admin-pass-2026` diff --git a/README_PRODUCTION.md b/README_PRODUCTION.md index a8b1c95..89b6619 100644 --- a/README_PRODUCTION.md +++ b/README_PRODUCTION.md @@ -5,6 +5,7 @@ Follow these steps to deploy your Smart Traffic & Parking system to the cloud fo --- ### Step 1: Create a Cloud Database (5 mins) + 1. Go to [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) and create a free account. 2. Create a new Cluster (Shared/Free). 3. Under **Network Access**, allow access from "Everywhere" (0.0.0.0/0). @@ -15,6 +16,7 @@ Follow these steps to deploy your Smart Traffic & Parking system to the cloud fo --- ### Step 2: Prepare for Upload + 1. Open the project folder on your computer. 2. **DELETE** the `node_modules` folders (both in root and inside `server`). These are very large and reconstructed in the cloud. 3. **DELETE** the `.env` files (keep them safe on your PC, you will copy the values into the cloud dashboard later). @@ -23,6 +25,7 @@ Follow these steps to deploy your Smart Traffic & Parking system to the cloud fo --- ### Step 3: Deploy Backend (Render.com) + 1. Go to [Render](https://render.com) and sign up (GitHub login recommended). 2. Click **New** > **Web Service**. 3. You can either connect a GitHub repo or use "Manual Deploy" by uploading your ZIP. @@ -36,6 +39,7 @@ Follow these steps to deploy your Smart Traffic & Parking system to the cloud fo --- ### Step 4: Deploy Frontend (Vercel.com) + 1. Go to [Vercel](https://vercel.com) and sign up. 2. Click **Add New** > **Project**. 3. Upload your project folder or connect GitHub. @@ -47,4 +51,5 @@ Follow these steps to deploy your Smart Traffic & Parking system to the cloud fo --- ### ✅ Your Permanent Link + Once Step 4 is done, Vercel will give you a permanent link (e.g. `traffitech.vercel.app`) that works **24/7**! diff --git a/eslint.config.js b/eslint.config.js index d291aa3..e86d696 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -27,7 +27,10 @@ export default defineConfig([ }, }, rules: { - 'no-unused-vars': ['warn', { varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^_' }], + 'no-unused-vars': [ + 'warn', + { varsIgnorePattern: '^[A-Z_]|motion', argsIgnorePattern: '^[A-Z_]', caughtErrors: 'none' }, + ], 'no-debugger': 'error', 'no-duplicate-imports': 'error', 'no-console': 'off', @@ -60,7 +63,10 @@ export default defineConfig([ }, }, rules: { - 'no-unused-vars': ['warn', { varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^_' }], + 'no-unused-vars': [ + 'warn', + { varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^[A-Z_]', caughtErrors: 'none' }, + ], 'no-debugger': 'error', // Allow console in server/backend code (needed for server logs) 'no-console': 'off', @@ -93,4 +99,3 @@ export default defineConfig([ }, }, ]); - diff --git a/index.html b/index.html index 02680fb..1c2068a 100644 --- a/index.html +++ b/index.html @@ -1,27 +1,32 @@ + + + + + + - - - - - - + + TraffiTech | Smart Traffic & Parking + + + + + + - - TraffiTech | Smart Traffic & Parking - - - - - - - - -
- - - - \ No newline at end of file + +
+ + + diff --git a/postcss.config.js b/postcss.config.js index d41ad63..2aa7205 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -1,6 +1,6 @@ export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/server/config/adminSecret.js b/server/config/adminSecret.js index cb0df96..3fdb9d2 100644 --- a/server/config/adminSecret.js +++ b/server/config/adminSecret.js @@ -1,16 +1,14 @@ -const crypto = require('crypto'); - let devAdminSecret = null; const getAdminSecret = () => { - if (process.env.ADMIN_SECRET_KEY) { - return process.env.ADMIN_SECRET_KEY; - } - - if (!devAdminSecret) { - devAdminSecret = process.env.ADMIN_SECRET_KEY || 'traffitech-admin-2026'; - } - return devAdminSecret; + if (process.env.ADMIN_SECRET_KEY) { + return process.env.ADMIN_SECRET_KEY; + } + + if (!devAdminSecret) { + devAdminSecret = process.env.ADMIN_SECRET_KEY || 'traffitech-admin-2026'; + } + return devAdminSecret; }; module.exports = { getAdminSecret }; diff --git a/server/config/jwt.js b/server/config/jwt.js index 6b4d6c2..6fe56c3 100644 --- a/server/config/jwt.js +++ b/server/config/jwt.js @@ -3,21 +3,23 @@ const crypto = require('crypto'); let devSecret = null; const getJwtSecret = () => { - if (process.env.JWT_SECRET) { - return process.env.JWT_SECRET; - } + if (process.env.JWT_SECRET) { + return process.env.JWT_SECRET; + } - if (process.env.NODE_ENV === 'production') { - console.error("FATAL ERROR: JWT_SECRET environment variable is required in production!"); - process.exit(1); - } + if (process.env.NODE_ENV === 'production') { + console.error('FATAL ERROR: JWT_SECRET environment variable is required in production!'); + process.exit(1); + } - // In local development mode without JWT_SECRET, generate a random ephemeral secret per boot - if (!devSecret) { - devSecret = crypto.randomBytes(32).toString('hex'); - console.warn("⚠️ Warning: JWT_SECRET environment variable is missing. Generated ephemeral local secret."); - } - return devSecret; + // In local development mode without JWT_SECRET, generate a random ephemeral secret per boot + if (!devSecret) { + devSecret = crypto.randomBytes(32).toString('hex'); + console.warn( + '⚠️ Warning: JWT_SECRET environment variable is missing. Generated ephemeral local secret.' + ); + } + return devSecret; }; module.exports = { getJwtSecret }; diff --git a/server/index.js b/server/index.js index fc819c0..dbe6229 100644 --- a/server/index.js +++ b/server/index.js @@ -12,10 +12,10 @@ dotenv.config({ path: path.join(__dirname, '.env') }); const app = express(); const server = require('http').createServer(app); const io = require('socket.io')(server, { - cors: { - origin: "*", - methods: ["GET", "POST"] - } + cors: { + origin: '*', + methods: ['GET', 'POST'], + }, }); // Initialize Simulation Service @@ -23,7 +23,7 @@ const simulation = new SimulationService(io); simulation.start(); io.on('connection', (socket) => { - console.log('Client connected for IoT stream:', socket.id); + console.log('Client connected for IoT stream:', socket.id); }); // Middleware @@ -32,17 +32,20 @@ app.use(express.json()); // Hybrid Connection Logic const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/traffitech'; -mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 4000 }) - .then(() => console.log('✅ Connected to MongoDB Atlas (Production Cloud DB)')) - .catch((err) => { - console.warn('⚠️ MongoDB Atlas connection error details:', err?.message || err); - console.warn('⚠️ Using Local JSON DB fallback.'); - if (process.env.NODE_ENV === 'production' || process.env.RENDER === 'true') { - console.warn('🚨 PRODUCTION PERSISTENCE WARNING: MONGODB_URI is not connected in production mode. Data written to JSON fallback DB will be ephemeral across server restarts on Render. Ensure MONGODB_URI is configured in Render environment variables for cloud persistence.'); - } else { - console.log('✅ Zero-Dependency Fallback Mode Active'); - } - }); +mongoose + .connect(MONGODB_URI, { serverSelectionTimeoutMS: 4000 }) + .then(() => console.log('✅ Connected to MongoDB Atlas (Production Cloud DB)')) + .catch((err) => { + console.warn('⚠️ MongoDB Atlas connection error details:', err?.message || err); + console.warn('⚠️ Using Local JSON DB fallback.'); + if (process.env.NODE_ENV === 'production' || process.env.RENDER === 'true') { + console.warn( + '🚨 PRODUCTION PERSISTENCE WARNING: MONGODB_URI is not connected in production mode. Data written to JSON fallback DB will be ephemeral across server restarts on Render. Ensure MONGODB_URI is configured in Render environment variables for cloud persistence.' + ); + } else { + console.log('✅ Zero-Dependency Fallback Mode Active'); + } + }); // Routes app.use('/api/auth', require('./routes/auth')); @@ -53,31 +56,36 @@ app.use('/api/rapids-analytics', require('./routes/rapidsAnalytics')); // Basic Route app.get('/', (req, res) => { - res.json({ - message: 'TraffiTech API is running', - mode: mongoose.connection.readyState === 1 ? 'Production (Cloud DB)' : 'Development (Fallback JSON DB)' - }); + res.json({ + message: 'TraffiTech API is running', + mode: + mongoose.connection.readyState === 1 + ? 'Production (Cloud DB)' + : 'Development (Fallback JSON DB)', + }); }); // Port Configuration const PORT = process.env.PORT || 5000; server.listen(PORT, '0.0.0.0', () => { - console.log(`🚀 Server running on port ${PORT} (0.0.0.0 interface bound)`); + console.log(`🚀 Server running on port ${PORT} (0.0.0.0 interface bound)`); - // Environment Variables Audit Log on Boot - const isProdEnv = process.env.NODE_ENV === 'production' || process.env.RENDER === 'true'; - if (isProdEnv) { - const missingKeys = []; - if (!process.env.JWT_SECRET) missingKeys.push('JWT_SECRET'); - if (!process.env.ADMIN_SECRET_KEY) missingKeys.push('ADMIN_SECRET_KEY'); - if (!process.env.STRIPE_SECRET_KEY) missingKeys.push('STRIPE_SECRET_KEY'); - if (!process.env.STRIPE_WEBHOOK_SECRET) missingKeys.push('STRIPE_WEBHOOK_SECRET'); - if (!process.env.MONGODB_URI) missingKeys.push('MONGODB_URI'); + // Environment Variables Audit Log on Boot + const isProdEnv = process.env.NODE_ENV === 'production' || process.env.RENDER === 'true'; + if (isProdEnv) { + const missingKeys = []; + if (!process.env.JWT_SECRET) missingKeys.push('JWT_SECRET'); + if (!process.env.ADMIN_SECRET_KEY) missingKeys.push('ADMIN_SECRET_KEY'); + if (!process.env.STRIPE_SECRET_KEY) missingKeys.push('STRIPE_SECRET_KEY'); + if (!process.env.STRIPE_WEBHOOK_SECRET) missingKeys.push('STRIPE_WEBHOOK_SECRET'); + if (!process.env.MONGODB_URI) missingKeys.push('MONGODB_URI'); - if (missingKeys.length > 0) { - console.warn(`⚠️ PRODUCTION ENV CONFIG NOTICE: Missing Render environment variables: ${missingKeys.join(', ')}`); - } else { - console.log('✅ Production Environment Audit Passed: All production secrets configured.'); - } + if (missingKeys.length > 0) { + console.warn( + `⚠️ PRODUCTION ENV CONFIG NOTICE: Missing Render environment variables: ${missingKeys.join(', ')}` + ); + } else { + console.log('✅ Production Environment Audit Passed: All production secrets configured.'); } + } }); diff --git a/server/middleware/admin.js b/server/middleware/admin.js index 361bdcc..beabcc7 100644 --- a/server/middleware/admin.js +++ b/server/middleware/admin.js @@ -1,7 +1,7 @@ module.exports = function (req, res, next) { - if (req.user && req.user.role === 'admin') { - next(); - } else { - res.status(403).json({ message: 'Access denied. Admin privileges required.' }); - } + if (req.user && req.user.role === 'admin') { + next(); + } else { + res.status(403).json({ message: 'Access denied. Admin privileges required.' }); + } }; diff --git a/server/middleware/auth.js b/server/middleware/auth.js index 061d618..07f2e64 100644 --- a/server/middleware/auth.js +++ b/server/middleware/auth.js @@ -2,20 +2,20 @@ const jwt = require('jsonwebtoken'); const { getJwtSecret } = require('../config/jwt'); module.exports = function (req, res, next) { - // Get token from header - const token = req.header('x-auth-token'); + // Get token from header + const token = req.header('x-auth-token'); - // Check if no token - if (!token) { - return res.status(401).json({ message: 'No token, authorization denied' }); - } + // Check if no token + if (!token) { + return res.status(401).json({ message: 'No token, authorization denied' }); + } - // Verify token - try { - const decoded = jwt.verify(token, getJwtSecret()); - req.user = decoded; - next(); - } catch (err) { - res.status(401).json({ message: `Token is not valid: ${err.message}` }); - } + // Verify token + try { + const decoded = jwt.verify(token, getJwtSecret()); + req.user = decoded; + next(); + } catch (err) { + res.status(401).json({ message: `Token is not valid: ${err.message}` }); + } }; diff --git a/server/models/Booking.js b/server/models/Booking.js index ebaa36d..472255b 100644 --- a/server/models/Booking.js +++ b/server/models/Booking.js @@ -5,128 +5,160 @@ const jsonDb = new JsonDB('bookings'); // 1. Mongoose Schema const bookingSchema = new mongoose.Schema({ - user: { type: mongoose.Schema.Types.Mixed, ref: 'User' }, - userEmail: String, - bookingId: { type: String, required: true }, - slotId: { type: String, required: true }, - parkingZone: mongoose.Schema.Types.Mixed, - date: { type: String, required: true }, - startTime: String, - endTime: String, - duration: Number, - vehicleNumber: String, - vehicleType: String, - totalPrice: Number, - paymentStatus: { type: String, default: 'pending' }, - paymentId: String, - timestamp: { type: Date, default: Date.now } + user: { type: mongoose.Schema.Types.Mixed, ref: 'User' }, + userEmail: String, + bookingId: { type: String, required: true }, + slotId: { type: String, required: true }, + parkingZone: mongoose.Schema.Types.Mixed, + date: { type: String, required: true }, + startTime: String, + endTime: String, + duration: Number, + vehicleNumber: String, + vehicleType: String, + totalPrice: Number, + paymentStatus: { type: String, default: 'pending' }, + paymentId: String, + timestamp: { type: Date, default: Date.now }, }); const MongooseBooking = mongoose.models.Booking || mongoose.model('Booking', bookingSchema); // 2. Define Hybrid Wrapper class Booking { - static isMongoConnected() { - return mongoose.connection.readyState === 1; - } - - static async lock(fn) { - if (Booking.isMongoConnected()) { - return await fn(); - } - return await jsonDb.lock(fn); - } + static isMongoConnected() { + return mongoose.connection.readyState === 1; + } - static async find(query) { - if (Booking.isMongoConnected()) { - const docs = await MongooseBooking.find(query); - return docs.map(d => new Booking(d.toObject ? d.toObject() : d)); - } - const results = await jsonDb.find(query); - return results.map(b => new Booking(b)); + static async lock(fn) { + if (Booking.isMongoConnected()) { + return await fn(); } + return await jsonDb.lock(fn); + } - static async findOne(query) { - if (Booking.isMongoConnected()) { - const doc = await MongooseBooking.findOne(query); - if (!doc) return null; - return new Booking(doc.toObject ? doc.toObject() : doc); - } - const booking = await jsonDb.findOne(query); - if (!booking) return null; - return new Booking(booking); + static async find(query) { + if (Booking.isMongoConnected()) { + const docs = await MongooseBooking.find(query); + return docs.map((d) => new Booking(d.toObject ? d.toObject() : d)); } - - static async findById(id) { - if (Booking.isMongoConnected()) { - const doc = await MongooseBooking.findById(id); - if (!doc) return null; - return new Booking(doc.toObject ? doc.toObject() : doc); - } - const booking = await jsonDb.findById(id); - if (!booking) return null; - return new Booking(booking); + const results = await jsonDb.find(query); + return results.map((b) => new Booking(b)); + } + + static async findOne(query) { + if (Booking.isMongoConnected()) { + const doc = await MongooseBooking.findOne(query); + if (!doc) return null; + return new Booking(doc.toObject ? doc.toObject() : doc); } - - constructor(data) { - this.data = data || {}; - if (this.data._id) { - this._id = this.data._id; - } + const booking = await jsonDb.findOne(query); + if (!booking) return null; + return new Booking(booking); + } + + static async findById(id) { + if (Booking.isMongoConnected()) { + const doc = await MongooseBooking.findById(id); + if (!doc) return null; + return new Booking(doc.toObject ? doc.toObject() : doc); } - - get _id() { return this.data._id; } - set _id(val) { this.data._id = val; } - get bookingId() { return this.data.bookingId; } - get slotId() { return this.data.slotId; } - get parkingZone() { return this.data.parkingZone; } - get date() { return this.data.date; } - get startTime() { return this.data.startTime; } - get endTime() { return this.data.endTime; } - get duration() { return this.data.duration; } - get totalPrice() { return this.data.totalPrice; } - get paymentStatus() { return this.data.paymentStatus; } - get paymentId() { return this.data.paymentId; } - get timestamp() { return this.data.timestamp; } - get user() { return this.data.user; } - get slot() { return this.data.slot; } - - toJSON() { - return this.data; + const booking = await jsonDb.findById(id); + if (!booking) return null; + return new Booking(booking); + } + + constructor(data) { + this.data = data || {}; + if (this.data._id) { + this._id = this.data._id; } - - set paymentStatus(val) { - this.data.paymentStatus = val; + } + + get _id() { + return this.data._id; + } + set _id(val) { + this.data._id = val; + } + get bookingId() { + return this.data.bookingId; + } + get slotId() { + return this.data.slotId; + } + get parkingZone() { + return this.data.parkingZone; + } + get date() { + return this.data.date; + } + get startTime() { + return this.data.startTime; + } + get endTime() { + return this.data.endTime; + } + get duration() { + return this.data.duration; + } + get totalPrice() { + return this.data.totalPrice; + } + get paymentStatus() { + return this.data.paymentStatus; + } + get paymentId() { + return this.data.paymentId; + } + get timestamp() { + return this.data.timestamp; + } + get user() { + return this.data.user; + } + get slot() { + return this.data.slot; + } + + toJSON() { + return this.data; + } + + set paymentStatus(val) { + this.data.paymentStatus = val; + } + + set paymentId(val) { + this.data.paymentId = val; + } + + async save() { + if (Booking.isMongoConnected()) { + if (this.data._id) { + const updated = await MongooseBooking.findByIdAndUpdate(this.data._id, this.data, { + new: true, + }); + const plain = updated ? (updated.toObject ? updated.toObject() : updated) : this.data; + this.data = plain; + return new Booking(plain); + } + const mongoBooking = new MongooseBooking(this.data); + const saved = await mongoBooking.save(); + const plain = saved.toObject ? saved.toObject() : saved; + this.data = plain; + return new Booking(plain); } - set paymentId(val) { - this.data.paymentId = val; + if (this.data._id) { + const updated = await jsonDb.update(this.data._id, this.data); + return new Booking(updated); } - async save() { - if (Booking.isMongoConnected()) { - if (this.data._id) { - const updated = await MongooseBooking.findByIdAndUpdate(this.data._id, this.data, { new: true }); - const plain = updated ? (updated.toObject ? updated.toObject() : updated) : this.data; - this.data = plain; - return new Booking(plain); - } - const mongoBooking = new MongooseBooking(this.data); - const saved = await mongoBooking.save(); - const plain = saved.toObject ? saved.toObject() : saved; - this.data = plain; - return new Booking(plain); - } - - if (this.data._id) { - const updated = await jsonDb.update(this.data._id, this.data); - return new Booking(updated); - } - - const saved = await jsonDb.create(this.data); - this.data._id = saved._id; - return new Booking(saved); - } + const saved = await jsonDb.create(this.data); + this.data._id = saved._id; + return new Booking(saved); + } } module.exports = Booking; diff --git a/server/models/User.js b/server/models/User.js index b26e071..38214a5 100644 --- a/server/models/User.js +++ b/server/models/User.js @@ -6,158 +6,162 @@ const jsonDb = new JsonDB('users'); // 1. Define Mongoose Schema (for MongoDB Atlas) const userSchema = new mongoose.Schema({ - username: { type: String, required: true, unique: true }, - email: { type: String, required: true, unique: true }, - password: { type: String, required: true }, - role: { type: String, default: 'user' }, - createdAt: { type: Date, default: Date.now } + username: { type: String, required: true, unique: true }, + email: { type: String, required: true, unique: true }, + password: { type: String, required: true }, + role: { type: String, default: 'user' }, + createdAt: { type: Date, default: Date.now }, }); userSchema.pre('save', async function (next) { - if (!this.isModified('password')) return next(); - const salt = await bcrypt.genSalt(10); - this.password = await bcrypt.hash(this.password, salt); - next(); + if (!this.isModified('password')) return next(); + const salt = await bcrypt.genSalt(10); + this.password = await bcrypt.hash(this.password, salt); + next(); }); userSchema.methods.comparePassword = async function (candidatePassword) { - return await bcrypt.compare(candidatePassword, this.password); + return await bcrypt.compare(candidatePassword, this.password); }; const MongooseUser = mongoose.models.User || mongoose.model('User', userSchema); // 2. Define Hybrid Wrapper class User { - static isMongoConnected() { - return mongoose.connection.readyState === 1; + static isMongoConnected() { + return mongoose.connection.readyState === 1; + } + + static async find(query = {}, projection = '') { + if (User.isMongoConnected()) { + const docs = await MongooseUser.find(query, projection); + const instances = docs.map((u) => new User(u.toObject ? u.toObject() : u)); + if (projection && projection.includes('-password')) { + instances.forEach((inst) => { + delete inst.data.password; + }); + } + return instances; } - - static async find(query = {}, projection = '') { - if (User.isMongoConnected()) { - const docs = await MongooseUser.find(query, projection); - const instances = docs.map(u => new User(u.toObject ? u.toObject() : u)); - if (projection && projection.includes('-password')) { - instances.forEach(inst => { - delete inst.data.password; - }); - } - return instances; - } - const results = await jsonDb.find(query); - const instances = results.map(u => new User(u)); - if (projection && projection.includes('-password')) { - instances.forEach(inst => { - delete inst.data.password; - }); - } - return instances; - } - - static async findOne(query) { - if (User.isMongoConnected()) { - const doc = await MongooseUser.findOne(query); - if (!doc) return null; - return new User(doc.toObject ? doc.toObject() : doc); - } - - if (query && query.$or && Array.isArray(query.$or)) { - const allUsers = await jsonDb.find({}); - const match = allUsers.find(u => query.$or.some(subQuery => { - return Object.keys(subQuery).every(key => u[key] === subQuery[key]); - })); - if (!match) return null; - return new User(match); - } - - const user = await jsonDb.findOne(query); - if (!user) return null; - return new User(user); - } - - static async findById(id) { - if (User.isMongoConnected()) { - const doc = await MongooseUser.findById(id); - if (!doc) return null; - return new User(doc.toObject ? doc.toObject() : doc); - } - const user = await jsonDb.findById(id); - if (!user) return null; - return new User(user); - } - - constructor(data) { - this.data = { role: 'user', ...data }; - // Expose top level fields directly or via getter/setter to match mongoose objects - if (this.data._id) { - this._id = this.data._id; - } + const results = await jsonDb.find(query); + const instances = results.map((u) => new User(u)); + if (projection && projection.includes('-password')) { + instances.forEach((inst) => { + delete inst.data.password; + }); } - - get _id() { - return this.data._id; + return instances; + } + + static async findOne(query) { + if (User.isMongoConnected()) { + const doc = await MongooseUser.findOne(query); + if (!doc) return null; + return new User(doc.toObject ? doc.toObject() : doc); } - set _id(val) { - this.data._id = val; + if (query && query.$or && Array.isArray(query.$or)) { + const allUsers = await jsonDb.find({}); + const match = allUsers.find((u) => + query.$or.some((subQuery) => { + return Object.keys(subQuery).every((key) => u[key] === subQuery[key]); + }) + ); + if (!match) return null; + return new User(match); } - get role() { - return this.data.role; - } + const user = await jsonDb.findOne(query); + if (!user) return null; + return new User(user); + } - get username() { - return this.data.username; + static async findById(id) { + if (User.isMongoConnected()) { + const doc = await MongooseUser.findById(id); + if (!doc) return null; + return new User(doc.toObject ? doc.toObject() : doc); } - - get email() { - return this.data.email; + const user = await jsonDb.findById(id); + if (!user) return null; + return new User(user); + } + + constructor(data) { + this.data = { role: 'user', ...data }; + // Expose top level fields directly or via getter/setter to match mongoose objects + if (this.data._id) { + this._id = this.data._id; } - - get password() { - return this.data.password; + } + + get _id() { + return this.data._id; + } + + set _id(val) { + this.data._id = val; + } + + get role() { + return this.data.role; + } + + get username() { + return this.data.username; + } + + get email() { + return this.data.email; + } + + get password() { + return this.data.password; + } + + async comparePassword(candidatePassword) { + // Safe check for hashed passwords + const hash = this.data.password || ''; + return await bcrypt.compare(candidatePassword, hash); + } + + toJSON() { + return this.data; + } + + async save() { + if (User.isMongoConnected()) { + if (this.data._id) { + const updated = await MongooseUser.findByIdAndUpdate(this.data._id, this.data, { + new: true, + }); + const plain = updated ? (updated.toObject ? updated.toObject() : updated) : this.data; + this.data = plain; + return new User(plain); + } + const mongoUser = new MongooseUser(this.data); + const saved = await mongoUser.save(); + const plain = saved.toObject ? saved.toObject() : saved; + this.data = plain; + return new User(plain); } - async comparePassword(candidatePassword) { - // Safe check for hashed passwords - const hash = this.data.password || ''; - return await bcrypt.compare(candidatePassword, hash); + // JSON Fallback + if (this.data.password && !this.data.password.startsWith('$2a$')) { + const salt = await bcrypt.genSalt(10); + this.data.password = await bcrypt.hash(this.data.password, salt); } - toJSON() { - return this.data; + if (this.data._id) { + const updated = await jsonDb.update(this.data._id, this.data); + return new User(updated); } - async save() { - if (User.isMongoConnected()) { - if (this.data._id) { - const updated = await MongooseUser.findByIdAndUpdate(this.data._id, this.data, { new: true }); - const plain = updated ? (updated.toObject ? updated.toObject() : updated) : this.data; - this.data = plain; - return new User(plain); - } - const mongoUser = new MongooseUser(this.data); - const saved = await mongoUser.save(); - const plain = saved.toObject ? saved.toObject() : saved; - this.data = plain; - return new User(plain); - } - - // JSON Fallback - if (this.data.password && !this.data.password.startsWith('$2a$')) { - const salt = await bcrypt.genSalt(10); - this.data.password = await bcrypt.hash(this.data.password, salt); - } - - if (this.data._id) { - const updated = await jsonDb.update(this.data._id, this.data); - return new User(updated); - } - - const saved = await jsonDb.create(this.data); - this.data._id = saved._id; - this._id = saved._id; - return new User(saved); - } + const saved = await jsonDb.create(this.data); + this.data._id = saved._id; + this._id = saved._id; + return new User(saved); + } } module.exports = User; diff --git a/server/package.json b/server/package.json index 5df3257..e076df0 100644 --- a/server/package.json +++ b/server/package.json @@ -10,10 +10,16 @@ "test:coverage": "jest --coverage --testEnvironment node" }, "jest": { - "testMatch": ["**/tests/**/*.test.js"], + "testMatch": [ + "**/tests/**/*.test.js" + ], "testEnvironment": "node", "coverageDirectory": "coverage", - "collectCoverageFrom": ["*.js", "routes/**/*.js", "utils/**/*.js"] + "collectCoverageFrom": [ + "*.js", + "routes/**/*.js", + "utils/**/*.js" + ] }, "keywords": [], "author": "", @@ -34,4 +40,4 @@ "nodemon": "^3.1.11", "supertest": "^7.1.0" } -} \ No newline at end of file +} diff --git a/server/routes/auth.js b/server/routes/auth.js index f559bdd..1c46934 100644 --- a/server/routes/auth.js +++ b/server/routes/auth.js @@ -4,70 +4,77 @@ const User = require('../models/User'); const admin = require('../middleware/admin'); const auth = require('../middleware/auth'); const { getJwtSecret } = require('../config/jwt'); -const { getAdminSecret } = require('../config/adminSecret'); const router = express.Router(); // Register User router.post('/register', async (req, res) => { - try { - const { username, email, password, role, adminSecret } = req.body; + try { + const { username, email, password, role } = req.body; - let user = await User.findOne({ $or: [{ email }, { username }] }); - if (user) { - return res.status(400).json({ message: 'User already exists' }); - } + let user = await User.findOne({ $or: [{ email }, { username }] }); + if (user) { + return res.status(400).json({ message: 'User already exists' }); + } - let userRole = 'user'; - if (role === 'admin') { - userRole = 'admin'; - } + let userRole = 'user'; + if (role === 'admin') { + userRole = 'admin'; + } - user = new User({ username, email, password, role: userRole }); - await user.save(); + user = new User({ username, email, password, role: userRole }); + await user.save(); - const token = jwt.sign({ id: user._id, role: userRole }, getJwtSecret(), { expiresIn: '7d' }); - res.status(201).json({ token, user: { id: user._id, username: user.username, email: user.email, role: userRole } }); - } catch (err) { - res.status(500).json({ message: 'Server error', error: err.message }); - } + const token = jwt.sign({ id: user._id, role: userRole }, getJwtSecret(), { expiresIn: '7d' }); + res.status(201).json({ + token, + user: { id: user._id, username: user.username, email: user.email, role: userRole }, + }); + } catch (err) { + res.status(500).json({ message: 'Server error', error: err.message }); + } }); // Login User router.post('/login', async (req, res) => { - try { - const { email, password, role } = req.body; - - const user = await User.findOne({ email }); - if (!user) { - return res.status(400).json({ message: 'Invalid credentials' }); - } + try { + const { email, password, role } = req.body; - const isMatch = await user.comparePassword(password); - if (!isMatch) { - return res.status(400).json({ message: 'Invalid credentials' }); - } + const user = await User.findOne({ email }); + if (!user) { + return res.status(400).json({ message: 'Invalid credentials' }); + } - // Strict role validation: Always enforce the role stored in DB - const storedRole = user.role || 'user'; - if (role === 'admin' && storedRole !== 'admin') { - return res.status(403).json({ message: 'Access Denied: This account does not have Administrator privileges.' }); - } + const isMatch = await user.comparePassword(password); + if (!isMatch) { + return res.status(400).json({ message: 'Invalid credentials' }); + } - const token = jwt.sign({ id: user._id, role: storedRole }, getJwtSecret(), { expiresIn: '7d' }); - res.json({ token, user: { id: user._id, username: user.username, email: user.email, role: storedRole } }); - } catch (err) { - res.status(500).json({ message: 'Server error', error: err.message }); + // Strict role validation: Always enforce the role stored in DB + const storedRole = user.role || 'user'; + if (role === 'admin' && storedRole !== 'admin') { + return res + .status(403) + .json({ message: 'Access Denied: This account does not have Administrator privileges.' }); } + + const token = jwt.sign({ id: user._id, role: storedRole }, getJwtSecret(), { expiresIn: '7d' }); + res.json({ + token, + user: { id: user._id, username: user.username, email: user.email, role: storedRole }, + }); + } catch (err) { + res.status(500).json({ message: 'Server error', error: err.message }); + } }); // Get all users (Admin only) router.get('/', [auth, admin], async (req, res) => { - try { - const users = await User.find({}, '-password'); // Exclude passwords - res.json(users); - } catch (err) { - res.status(500).json({ message: 'Server error', error: err.message }); - } + try { + const users = await User.find({}, '-password'); // Exclude passwords + res.json(users); + } catch (err) { + res.status(500).json({ message: 'Server error', error: err.message }); + } }); module.exports = router; diff --git a/server/routes/bookings.js b/server/routes/bookings.js index 111da25..655f29c 100644 --- a/server/routes/bookings.js +++ b/server/routes/bookings.js @@ -6,273 +6,299 @@ const router = express.Router(); const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); const toPlain = (doc) => { - if (!doc) return null; - if (doc.data) return doc.data; - if (typeof doc.toObject === 'function') return doc.toObject(); - return doc; + if (!doc) return null; + if (doc.data) return doc.data; + if (typeof doc.toObject === 'function') return doc.toObject(); + return doc; }; // Get user bookings for each registered user router.get('/', auth, async (req, res) => { - try { - const userId = String(req.user.id || ''); - const userEmail = (req.user.email || '').toLowerCase(); - - const allBookings = await Booking.find({}); - const plainBookings = allBookings.map(toPlain); - - // Admins can see all bookings across all users - if (req.user.role === 'admin') { - const sortedAdmin = plainBookings.sort((a, b) => { - const aTime = a.timestamp || a.createdAt || 0; - const bTime = b.timestamp || b.createdAt || 0; - return new Date(bTime) - new Date(aTime); - }); - return res.json(sortedAdmin); - } - - const userBookings = plainBookings.filter(b => { - if (!b) return false; - - // Match user ID (handling string, number, or object representation) - const bUser = b.user; - const bUserId = typeof bUser === 'object' ? String(bUser.id || bUser._id || '') : String(bUser || ''); - if (bUserId && userId && bUserId === userId) return true; - - // Match user email fallback - const bEmail = (b.userEmail || b.email || (typeof bUser === 'object' ? bUser.email : '') || '').toLowerCase(); - if (userEmail && bEmail && bEmail === userEmail) return true; - - return false; - }); - - // Sort manually by timestamp desc - const sorted = userBookings.sort((a, b) => { - const aTime = a.timestamp || a.createdAt || 0; - const bTime = b.timestamp || b.createdAt || 0; - return new Date(bTime) - new Date(aTime); - }); - res.json(sorted); - } catch (err) { - res.status(500).json({ message: err.message || 'Server error', error: err.message }); + try { + const userId = String(req.user.id || ''); + const userEmail = (req.user.email || '').toLowerCase(); + + const allBookings = await Booking.find({}); + const plainBookings = allBookings.map(toPlain); + + // Admins can see all bookings across all users + if (req.user.role === 'admin') { + const sortedAdmin = plainBookings.sort((a, b) => { + const aTime = a.timestamp || a.createdAt || 0; + const bTime = b.timestamp || b.createdAt || 0; + return new Date(bTime) - new Date(aTime); + }); + return res.json(sortedAdmin); } + + const userBookings = plainBookings.filter((b) => { + if (!b) return false; + + // Match user ID (handling string, number, or object representation) + const bUser = b.user; + const bUserId = + typeof bUser === 'object' ? String(bUser.id || bUser._id || '') : String(bUser || ''); + if (bUserId && userId && bUserId === userId) return true; + + // Match user email fallback + const bEmail = ( + b.userEmail || + b.email || + (typeof bUser === 'object' ? bUser.email : '') || + '' + ).toLowerCase(); + if (userEmail && bEmail && bEmail === userEmail) return true; + + return false; + }); + + // Sort manually by timestamp desc + const sorted = userBookings.sort((a, b) => { + const aTime = a.timestamp || a.createdAt || 0; + const bTime = b.timestamp || b.createdAt || 0; + return new Date(bTime) - new Date(aTime); + }); + res.json(sorted); + } catch (err) { + res.status(500).json({ message: err.message || 'Server error', error: err.message }); + } }); // Get active slots for a zone on a given date (real-time database state - Protected) router.get('/active-slots', auth, async (req, res) => { - const { zoneId, date } = req.query; - try { - const queryDate = date || new Date().toISOString().split('T')[0]; - const bookings = await Booking.find({ date: queryDate }); - // Filter by zoneId and active status - const active = bookings.map(toPlain).filter(b => { - const bZone = b.parkingZone; - const bZoneId = typeof bZone === 'string' ? bZone : (bZone?.id || ''); - const hasZoneId = !zoneId || bZoneId === zoneId; - const isActive = b.paymentStatus === 'paid' || b.paymentStatus === 'pending' || b.paymentStatus === 'completed'; - return hasZoneId && isActive; - }); - - // Sanitize to exclude sensitive user data (vehicleNumber, user id) - const sanitized = active.map(b => ({ - slotId: b.slotId, - parkingZone: b.parkingZone, - date: b.date, - startTime: b.startTime, - endTime: b.endTime, - paymentStatus: b.paymentStatus - })); - - res.json(sanitized); - } catch (err) { - res.status(500).json({ message: err.message || 'Server error', error: err.message }); - } + const { zoneId, date } = req.query; + try { + const queryDate = date || new Date().toISOString().split('T')[0]; + const bookings = await Booking.find({ date: queryDate }); + // Filter by zoneId and active status + const active = bookings.map(toPlain).filter((b) => { + const bZone = b.parkingZone; + const bZoneId = typeof bZone === 'string' ? bZone : bZone?.id || ''; + const hasZoneId = !zoneId || bZoneId === zoneId; + const isActive = + b.paymentStatus === 'paid' || + b.paymentStatus === 'pending' || + b.paymentStatus === 'completed'; + return hasZoneId && isActive; + }); + + // Sanitize to exclude sensitive user data (vehicleNumber, user id) + const sanitized = active.map((b) => ({ + slotId: b.slotId, + parkingZone: b.parkingZone, + date: b.date, + startTime: b.startTime, + endTime: b.endTime, + paymentStatus: b.paymentStatus, + })); + + res.json(sanitized); + } catch (err) { + res.status(500).json({ message: err.message || 'Server error', error: err.message }); + } }); router.post('/', auth, async (req, res) => { - try { - const { slot, slotId: bodySlotId, date, startTime, endTime, parkingZone, duration } = req.body; - const zoneId = parkingZone?.id || ''; - const rawSlot = bodySlotId || slot?.id || slot?.title; - const slotId = (zoneId && rawSlot && !rawSlot.startsWith(zoneId)) ? `${zoneId}-${rawSlot}` : rawSlot; - - if (!slotId || !date || !startTime || !endTime) { - return res.status(400).json({ message: 'Missing booking details' }); - } - - // Execute overlap check and booking creation inside atomic lock queue - const savedBooking = await Booking.lock(async () => { - const bookings = await Booking.find({ date }); - const plainBookings = bookings.map(toPlain); - const hasOverlap = plainBookings.some(b => { - const bZoneId = b.parkingZone?.id; - - // Match slot and zone strictly - const isSameSlot = (b.slotId === slotId || b.slotId === slot?.title || b.slotId === slot?.id) && - (!zoneId || !bZoneId || bZoneId === zoneId); - if (!isSameSlot) return false; - - const isOverlap = b.startTime < endTime && b.endTime > startTime; - const isPaid = b.paymentStatus === 'paid' || b.paymentStatus === 'completed'; - const isRecentPending = b.paymentStatus === 'pending' && - (Date.now() - new Date(b.timestamp || Date.now()).getTime() < 15 * 60 * 1000); - return isOverlap && (isPaid || isRecentPending); - }); - - if (hasOverlap) { - const err = new Error('This slot is already reserved for the selected timeframe.'); - err.statusCode = 400; - throw err; - } - - // Calculate totalPrice securely on the server - const currentHour = new Date().getHours(); - const isPeakHour = (currentHour >= 9 && currentHour <= 11) || (currentHour >= 17 && currentHour <= 19); - const surgeMultiplier = isPeakHour ? 1.5 : 1; - const basePrice = parkingZone?.price || 50; - const calculatedPrice = Math.round((duration || 1) * basePrice * surgeMultiplier); - - const newBooking = new Booking({ - ...req.body, - bookingId: req.body.bookingId || `BK-${Date.now()}-${Math.random().toString(36).substr(2, 9).toUpperCase()}`, - slotId: slotId, - totalPrice: calculatedPrice, - user: req.user.id, - userEmail: req.user.email, - timestamp: new Date() - }); - - return await newBooking.save(); - }); - - res.status(201).json(toPlain(savedBooking)); - } catch (err) { - res.status(err.statusCode || 500).json({ message: err.message || 'Server error', error: err.message }); + try { + const { slot, slotId: bodySlotId, date, startTime, endTime, parkingZone, duration } = req.body; + const zoneId = parkingZone?.id || ''; + const rawSlot = bodySlotId || slot?.id || slot?.title; + const slotId = + zoneId && rawSlot && !rawSlot.startsWith(zoneId) ? `${zoneId}-${rawSlot}` : rawSlot; + + if (!slotId || !date || !startTime || !endTime) { + return res.status(400).json({ message: 'Missing booking details' }); } + + // Execute overlap check and booking creation inside atomic lock queue + const savedBooking = await Booking.lock(async () => { + const bookings = await Booking.find({ date }); + const plainBookings = bookings.map(toPlain); + const hasOverlap = plainBookings.some((b) => { + const bZoneId = b.parkingZone?.id; + + // Match slot and zone strictly + const isSameSlot = + (b.slotId === slotId || b.slotId === slot?.title || b.slotId === slot?.id) && + (!zoneId || !bZoneId || bZoneId === zoneId); + if (!isSameSlot) return false; + + const isOverlap = b.startTime < endTime && b.endTime > startTime; + const isPaid = b.paymentStatus === 'paid' || b.paymentStatus === 'completed'; + const isRecentPending = + b.paymentStatus === 'pending' && + Date.now() - new Date(b.timestamp || Date.now()).getTime() < 15 * 60 * 1000; + return isOverlap && (isPaid || isRecentPending); + }); + + if (hasOverlap) { + const err = new Error('This slot is already reserved for the selected timeframe.'); + err.statusCode = 400; + throw err; + } + + // Calculate totalPrice securely on the server + const currentHour = new Date().getHours(); + const isPeakHour = + (currentHour >= 9 && currentHour <= 11) || (currentHour >= 17 && currentHour <= 19); + const surgeMultiplier = isPeakHour ? 1.5 : 1; + const basePrice = parkingZone?.price || 50; + const calculatedPrice = Math.round((duration || 1) * basePrice * surgeMultiplier); + + const newBooking = new Booking({ + ...req.body, + bookingId: + req.body.bookingId || + `BK-${Date.now()}-${Math.random().toString(36).substr(2, 9).toUpperCase()}`, + slotId: slotId, + totalPrice: calculatedPrice, + user: req.user.id, + userEmail: req.user.email, + timestamp: new Date(), + }); + + return await newBooking.save(); + }); + + res.status(201).json(toPlain(savedBooking)); + } catch (err) { + res + .status(err.statusCode || 500) + .json({ message: err.message || 'Server error', error: err.message }); + } }); // Update booking details (e.g. paymentStatus, vehicleId) - Protected with Server-Side Stripe Verification router.put('/:id', auth, async (req, res) => { - try { - const booking = await Booking.findById(req.params.id); - if (!booking) { - return res.status(404).json({ message: 'Booking not found' }); - } + try { + const booking = await Booking.findById(req.params.id); + if (!booking) { + return res.status(404).json({ message: 'Booking not found' }); + } - const plain = toPlain(booking); - const userId = String(plain.user || ''); - if (userId !== String(req.user.id) && req.user.role !== 'admin') { - return res.status(403).json({ message: 'Not authorized to update this booking' }); - } + const plain = toPlain(booking); + const userId = String(plain.user || ''); + if (userId !== String(req.user.id) && req.user.role !== 'admin') { + return res.status(403).json({ message: 'Not authorized to update this booking' }); + } - const { paymentStatus, paymentId, paymentMethod, paidAt } = req.body; - - // If client requests marking booking as completed/paid - if (paymentStatus === 'completed' || paymentStatus === 'paid') { - const isProduction = process.env.NODE_ENV === 'production' || process.env.RENDER === 'true' || !!process.env.STRIPE_SECRET_KEY; - - // Strict Deny-By-Default: Require valid, Stripe-verified pi_... PaymentIntent ID - if (isProduction) { - if (!paymentId || !String(paymentId).startsWith('pi_')) { - return res.status(400).json({ - message: 'Payment verification failed: A valid, verified Stripe PaymentIntent ID (starting with pi_) is required to mark a booking as completed.' - }); - } - if (!process.env.STRIPE_SECRET_KEY) { - return res.status(500).json({ - message: 'Server configuration error: STRIPE_SECRET_KEY environment variable is required to verify real Stripe transactions.' - }); - } - try { - const intent = await stripe.paymentIntents.retrieve(paymentId); - if (intent.status !== 'succeeded') { - return res.status(400).json({ - message: `Payment verification failed. Stripe PaymentIntent status is '${intent.status}', expected 'succeeded'.` - }); - } - } catch (stripeErr) { - return res.status(400).json({ - message: 'Payment verification failed: Invalid or unverified Stripe PaymentIntent.', - error: stripeErr.message - }); - } - } else { - // Non-production local development fallback check - if (!paymentId) { - return res.status(400).json({ message: 'Payment verification failed: Missing paymentId.' }); - } - } + const { paymentStatus, paymentId, paymentMethod, paidAt } = req.body; + + // If client requests marking booking as completed/paid + if (paymentStatus === 'completed' || paymentStatus === 'paid') { + const isProduction = + process.env.NODE_ENV === 'production' || + process.env.RENDER === 'true' || + !!process.env.STRIPE_SECRET_KEY; + + // Strict Deny-By-Default: Require valid, Stripe-verified pi_... PaymentIntent ID + if (isProduction) { + if (!paymentId || !String(paymentId).startsWith('pi_')) { + return res.status(400).json({ + message: + 'Payment verification failed: A valid, verified Stripe PaymentIntent ID (starting with pi_) is required to mark a booking as completed.', + }); + } + if (!process.env.STRIPE_SECRET_KEY) { + return res.status(500).json({ + message: + 'Server configuration error: STRIPE_SECRET_KEY environment variable is required to verify real Stripe transactions.', + }); } + try { + const intent = await stripe.paymentIntents.retrieve(paymentId); + if (intent.status !== 'succeeded') { + return res.status(400).json({ + message: `Payment verification failed. Stripe PaymentIntent status is '${intent.status}', expected 'succeeded'.`, + }); + } + } catch (stripeErr) { + return res.status(400).json({ + message: 'Payment verification failed: Invalid or unverified Stripe PaymentIntent.', + error: stripeErr.message, + }); + } + } else { + // Non-production local development fallback check + if (!paymentId) { + return res + .status(400) + .json({ message: 'Payment verification failed: Missing paymentId.' }); + } + } + } - if (paymentStatus) booking.paymentStatus = paymentStatus; - if (paymentId) booking.paymentId = paymentId; - if (paymentMethod) booking.paymentMethod = paymentMethod; - if (paidAt) booking.paidAt = paidAt; + if (paymentStatus) booking.paymentStatus = paymentStatus; + if (paymentId) booking.paymentId = paymentId; + if (paymentMethod) booking.paymentMethod = paymentMethod; + if (paidAt) booking.paidAt = paidAt; - const updated = await booking.save(); - res.json(toPlain(updated)); - } catch (err) { - res.status(500).json({ message: err.message || 'Server error', error: err.message }); - } + const updated = await booking.save(); + res.json(toPlain(updated)); + } catch (err) { + res.status(500).json({ message: err.message || 'Server error', error: err.message }); + } }); // Cancel a booking and process Stripe refund router.post('/:id/cancel', auth, async (req, res) => { - try { - const booking = await Booking.findById(req.params.id); - if (!booking) { - return res.status(404).json({ message: 'Booking not found' }); - } - - const plain = toPlain(booking); - const userId = String(plain.user || ''); - if (userId !== String(req.user.id) && req.user.role !== 'admin') { - return res.status(403).json({ message: 'Not authorized to cancel this booking' }); - } + try { + const booking = await Booking.findById(req.params.id); + if (!booking) { + return res.status(404).json({ message: 'Booking not found' }); + } - const currentPaymentStatus = plain.paymentStatus; - const currentPaymentId = plain.paymentId; + const plain = toPlain(booking); + const userId = String(plain.user || ''); + if (userId !== String(req.user.id) && req.user.role !== 'admin') { + return res.status(403).json({ message: 'Not authorized to cancel this booking' }); + } - if (currentPaymentStatus === 'cancelled' || currentPaymentStatus === 'refunded') { - return res.status(400).json({ message: 'Booking is already cancelled' }); - } + const currentPaymentStatus = plain.paymentStatus; + const currentPaymentId = plain.paymentId; - // Process refund via Stripe if paid - if (currentPaymentStatus === 'paid' && currentPaymentId) { - try { - await stripe.refunds.create({ - payment_intent: currentPaymentId - }); - booking.paymentStatus = 'refunded'; - } catch (stripeErr) { - console.error('Stripe Refund Error:', stripeErr); - return res.status(500).json({ message: 'Stripe refund transaction failed', error: stripeErr.message }); - } - } else { - booking.paymentStatus = 'cancelled'; - } + if (currentPaymentStatus === 'cancelled' || currentPaymentStatus === 'refunded') { + return res.status(400).json({ message: 'Booking is already cancelled' }); + } - const updated = await booking.save(); - res.json({ message: 'Booking cancelled and refunded successfully', booking: toPlain(updated) }); - } catch (err) { - res.status(500).json({ message: err.message || 'Server error', error: err.message }); + // Process refund via Stripe if paid + if (currentPaymentStatus === 'paid' && currentPaymentId) { + try { + await stripe.refunds.create({ + payment_intent: currentPaymentId, + }); + booking.paymentStatus = 'refunded'; + } catch (stripeErr) { + console.error('Stripe Refund Error:', stripeErr); + return res + .status(500) + .json({ message: 'Stripe refund transaction failed', error: stripeErr.message }); + } + } else { + booking.paymentStatus = 'cancelled'; } + + const updated = await booking.save(); + res.json({ message: 'Booking cancelled and refunded successfully', booking: toPlain(updated) }); + } catch (err) { + res.status(500).json({ message: err.message || 'Server error', error: err.message }); + } }); // Get all bookings (Admin only) router.get('/all', [auth, admin], async (req, res) => { - try { - const bookings = await Booking.find({}); - const plainBookings = bookings.map(toPlain); - const sorted = plainBookings.sort((a, b) => { - const aTime = a.timestamp || 0; - const bTime = b.timestamp || 0; - return new Date(bTime) - new Date(aTime); - }); - res.json(sorted); - } catch (err) { - res.status(500).json({ message: err.message || 'Server error', error: err.message }); - } + try { + const bookings = await Booking.find({}); + const plainBookings = bookings.map(toPlain); + const sorted = plainBookings.sort((a, b) => { + const aTime = a.timestamp || 0; + const bTime = b.timestamp || 0; + return new Date(bTime) - new Date(aTime); + }); + res.json(sorted); + } catch (err) { + res.status(500).json({ message: err.message || 'Server error', error: err.message }); + } }); module.exports = router; diff --git a/server/routes/payments.js b/server/routes/payments.js index 97902cd..6b78dee 100644 --- a/server/routes/payments.js +++ b/server/routes/payments.js @@ -5,54 +5,56 @@ const Booking = require('../models/Booking'); const router = express.Router(); const toPlain = (doc) => { - if (!doc) return null; - if (doc.data) return doc.data; - if (typeof doc.toObject === 'function') return doc.toObject(); - return doc; + if (!doc) return null; + if (doc.data) return doc.data; + if (typeof doc.toObject === 'function') return doc.toObject(); + return doc; }; // Create Payment Intent router.post('/create-payment-intent', auth, async (req, res) => { - try { - const { bookingId, currency = 'inr' } = req.body; - - if (!bookingId) { - return res.status(400).json({ message: 'Booking ID is required' }); - } - - // Fetch booking from database to get verified server-computed price - const booking = await Booking.findById(bookingId); - if (!booking) { - return res.status(404).json({ message: 'Booking not found' }); - } - - const plain = toPlain(booking); - // Ensure user owns the booking - const userId = String(plain.user || ''); - if (userId !== String(req.user.id)) { - return res.status(403).json({ message: 'Unauthorized access to this booking' }); - } - - const totalPrice = plain.totalPrice || 50; - - const paymentIntent = await stripe.paymentIntents.create({ - amount: Math.round(Number(totalPrice) * 100), // Secure verified amount - currency, - automatic_payment_methods: { - enabled: true, - }, - metadata: { - bookingId: String(plain._id || bookingId) // Inject metadata for Webhooks - } - }); - - res.json({ - clientSecret: paymentIntent.client_secret, - }); - } catch (err) { - console.error("Stripe Backend Error:", err); - res.status(500).json({ message: err.message || 'Failed to create Stripe PaymentIntent', error: err.stack }); + try { + const { bookingId, currency = 'inr' } = req.body; + + if (!bookingId) { + return res.status(400).json({ message: 'Booking ID is required' }); + } + + // Fetch booking from database to get verified server-computed price + const booking = await Booking.findById(bookingId); + if (!booking) { + return res.status(404).json({ message: 'Booking not found' }); } + + const plain = toPlain(booking); + // Ensure user owns the booking + const userId = String(plain.user || ''); + if (userId !== String(req.user.id)) { + return res.status(403).json({ message: 'Unauthorized access to this booking' }); + } + + const totalPrice = plain.totalPrice || 50; + + const paymentIntent = await stripe.paymentIntents.create({ + amount: Math.round(Number(totalPrice) * 100), // Secure verified amount + currency, + automatic_payment_methods: { + enabled: true, + }, + metadata: { + bookingId: String(plain._id || bookingId), // Inject metadata for Webhooks + }, + }); + + res.json({ + clientSecret: paymentIntent.client_secret, + }); + } catch (err) { + console.error('Stripe Backend Error:', err); + res + .status(500) + .json({ message: err.message || 'Failed to create Stripe PaymentIntent', error: err.stack }); + } }); module.exports = router; diff --git a/server/routes/rapidsAnalytics.js b/server/routes/rapidsAnalytics.js index 56fe871..d242e7e 100644 --- a/server/routes/rapidsAnalytics.js +++ b/server/routes/rapidsAnalytics.js @@ -12,114 +12,133 @@ const BENCHMARK_FILE = path.join(ANALYTICS_DIR, 'benchmark_results.json'); // Safe Helper to run python script using execFile (no shell execution, preventing command injection) const runPythonPipeline = (argsArray = []) => { - return new Promise((resolve, reject) => { - const pythonCmd = process.platform === 'win32' ? 'python' : 'python3'; - const scriptPath = path.join(__dirname, '..', 'analytics', 'pipeline.py'); - - console.log(`Executing pipeline via execFile: ${pythonCmd} ${scriptPath} ${argsArray.join(' ')}`); - execFile(pythonCmd, [scriptPath, ...argsArray], { cwd: path.join(__dirname, '..', '..') }, (error, stdout, stderr) => { - if (error) { - console.error(`Pipeline execution error: ${error.message}`); - console.error(`Pipeline stderr: ${stderr}`); - return reject(error); - } - resolve(stdout); - }); - }); + return new Promise((resolve, reject) => { + const pythonCmd = process.platform === 'win32' ? 'python' : 'python3'; + const scriptPath = path.join(__dirname, '..', 'analytics', 'pipeline.py'); + + console.log( + `Executing pipeline via execFile: ${pythonCmd} ${scriptPath} ${argsArray.join(' ')}` + ); + execFile( + pythonCmd, + [scriptPath, ...argsArray], + { cwd: path.join(__dirname, '..', '..') }, + (error, stdout, stderr) => { + if (error) { + console.error(`Pipeline execution error: ${error.message}`); + console.error(`Pipeline stderr: ${stderr}`); + return reject(error); + } + resolve(stdout); + } + ); + }); }; // GET /api/rapids-analytics/data (Protected: Admin Only) router.get('/data', [auth, admin], (req, res) => { - try { - if (!fs.existsSync(ANALYTICS_FILE) || !fs.existsSync(BENCHMARK_FILE)) { - return res.status(404).json({ message: 'Analytics data files not generated yet. Trigger a run first.' }); - } - - const analyticsData = JSON.parse(fs.readFileSync(ANALYTICS_FILE, 'utf8')); - const benchmarkData = JSON.parse(fs.readFileSync(BENCHMARK_FILE, 'utf8')); - - res.json({ - analytics: analyticsData, - benchmarks: benchmarkData - }); - } catch (error) { - console.error('Error fetching analytics cache:', error); - res.status(500).json({ message: 'Internal server error reading analytics cache' }); + try { + if (!fs.existsSync(ANALYTICS_FILE) || !fs.existsSync(BENCHMARK_FILE)) { + return res + .status(404) + .json({ message: 'Analytics data files not generated yet. Trigger a run first.' }); } + + const analyticsData = JSON.parse(fs.readFileSync(ANALYTICS_FILE, 'utf8')); + const benchmarkData = JSON.parse(fs.readFileSync(BENCHMARK_FILE, 'utf8')); + + res.json({ + analytics: analyticsData, + benchmarks: benchmarkData, + }); + } catch (error) { + console.error('Error fetching analytics cache:', error); + res.status(500).json({ message: 'Internal server error reading analytics cache' }); + } }); // POST /api/rapids-analytics/run-benchmark (Protected: Admin Only) router.post('/run-benchmark', [auth, admin], async (req, res) => { - try { - console.log('Starting live CPU vs GPU benchmark regeneration...'); - await runPythonPipeline(['--generate', '--size', '100000']); - - // Read new files - const analyticsData = JSON.parse(fs.readFileSync(ANALYTICS_FILE, 'utf8')); - const benchmarkData = JSON.parse(fs.readFileSync(BENCHMARK_FILE, 'utf8')); - - res.json({ - message: 'Benchmark pipeline ran successfully', - analytics: analyticsData, - benchmarks: benchmarkData - }); - } catch (error) { - console.error('Error running benchmark:', error); - res.status(500).json({ message: 'Failed to run python benchmark script' }); - } + try { + console.log('Starting live CPU vs GPU benchmark regeneration...'); + await runPythonPipeline(['--generate', '--size', '100000']); + + // Read new files + const analyticsData = JSON.parse(fs.readFileSync(ANALYTICS_FILE, 'utf8')); + const benchmarkData = JSON.parse(fs.readFileSync(BENCHMARK_FILE, 'utf8')); + + res.json({ + message: 'Benchmark pipeline ran successfully', + analytics: analyticsData, + benchmarks: benchmarkData, + }); + } catch (error) { + console.error('Error running benchmark:', error); + res.status(500).json({ message: 'Failed to run python benchmark script' }); + } }); // POST /api/rapids-analytics/query (Protected: Admin Only) router.post('/query', [auth, admin], async (req, res) => { - const { query } = req.body; - if (!query) { - return res.status(400).json({ message: 'Query string is required' }); - } - - try { - // Run python with query argument via execFile array (prevents shell command injection) - const output = await runPythonPipeline(['--query', query]); - - // Find JSON block in stdout - const jsonStart = output.indexOf('['); - const jsonEnd = output.lastIndexOf(']') + 1; - - if (jsonStart !== -1 && jsonEnd !== -1) { - const results = JSON.parse(output.substring(jsonStart, jsonEnd)); - res.json({ results }); - } else { - res.status(500).json({ message: 'Failed to parse SQL query outputs from pipeline', rawOutput: output }); - } - } catch (error) { - console.error('Error executing query:', error); - res.status(500).json({ message: 'Error executing query on traffic telemetry' }); + const { query } = req.body; + if (!query) { + return res.status(400).json({ message: 'Query string is required' }); + } + + try { + // Run python with query argument via execFile array (prevents shell command injection) + const output = await runPythonPipeline(['--query', query]); + + // Find JSON block in stdout + const jsonStart = output.indexOf('['); + const jsonEnd = output.lastIndexOf(']') + 1; + + if (jsonStart !== -1 && jsonEnd !== -1) { + const results = JSON.parse(output.substring(jsonStart, jsonEnd)); + res.json({ results }); + } else { + res + .status(500) + .json({ message: 'Failed to parse SQL query outputs from pipeline', rawOutput: output }); } + } catch (error) { + console.error('Error executing query:', error); + res.status(500).json({ message: 'Error executing query on traffic telemetry' }); + } }); // POST /api/rapids-analytics/gemini (Protected: Admin Only) router.post('/gemini', [auth, admin], async (req, res) => { - const { prompt, dataContext } = req.body; - const apiKey = process.env.GEMINI_API_KEY; - - if (!apiKey) { - console.warn('⚠️ GEMINI_API_KEY environment variable is not defined. Using high-fidelity mock AI Traffic Advisor fallback.'); - - // Construct a highly detailed simulated response based on the actual data context - let corridorsText = ''; - if (dataContext && dataContext.corridors) { - corridorsText = dataContext.corridors.map(c => - `- **${c.name}**: Avg Speed = ${c.avgSpeed} mph, Avg Vol = ${c.avgVolume} veh/min, Congestion Risk = ${c.congestionRisk}%, Recommended Tuning Offset = +${c.recommendedTuning}s.` - ).join('\n'); - } - - let bottlenecksText = ''; - if (dataContext && dataContext.bottlenecks) { - bottlenecksText = dataContext.bottlenecks.map(b => - `- **${b.intersectionId}** (${b.corridor}): Avg Speed = ${b.avgSpeed} mph, Risk = ${b.congestionRisk}%, recommended light offset = +${b.recommendedTuning}s.` - ).join('\n'); - } - - const mockResponse = `> ⚠️ **DEMO / SIMULATION MODE ACTIVE**: \`GEMINI_API_KEY\` is not configured in the backend environment. The figures and AI recommendations below are synthetic estimates generated for demonstration purposes. + const { prompt, dataContext } = req.body; + const apiKey = process.env.GEMINI_API_KEY; + + if (!apiKey) { + console.warn( + '⚠️ GEMINI_API_KEY environment variable is not defined. Using high-fidelity mock AI Traffic Advisor fallback.' + ); + + // Construct a highly detailed simulated response based on the actual data context + let corridorsText = ''; + if (dataContext && dataContext.corridors) { + corridorsText = dataContext.corridors + .map( + (c) => + `- **${c.name}**: Avg Speed = ${c.avgSpeed} mph, Avg Vol = ${c.avgVolume} veh/min, Congestion Risk = ${c.congestionRisk}%, Recommended Tuning Offset = +${c.recommendedTuning}s.` + ) + .join('\n'); + } + + let bottlenecksText = ''; + if (dataContext && dataContext.bottlenecks) { + bottlenecksText = dataContext.bottlenecks + .map( + (b) => + `- **${b.intersectionId}** (${b.corridor}): Avg Speed = ${b.avgSpeed} mph, Risk = ${b.congestionRisk}%, recommended light offset = +${b.recommendedTuning}s.` + ) + .join('\n'); + } + + const mockResponse = `> ⚠️ **DEMO / SIMULATION MODE ACTIVE**: \`GEMINI_API_KEY\` is not configured in the backend environment. The figures and AI recommendations below are synthetic estimates generated for demonstration purposes. ### 🚦 Gemini Enterprise Traffic Intelligence Report (Simulation Mode) @@ -140,41 +159,48 @@ ${bottlenecksText || '- No severe bottleneck intersections detected.'} - **Action Plan:** The Adaptive Signal Control autopilot is authorized to deploy the green-phase adjustments immediately. *Note: Configure your GEMINI_API_KEY in the backend .env to connect to live Gemini Enterprise Agent endpoints.*`; - - // Add a slight artificial delay to feel like a real network AI response - await new Promise(r => setTimeout(r, 1200)); - return res.json({ response: mockResponse }); - } - - try { - const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`; - const systemInstruction = "You are TraffiTech's Gemini Enterprise Traffic Advisor. You analyze urban traffic telemetry data (corridors, bottlenecks, speeds, risks, signal tuning) and provide detailed, structured diagnostic reports and actionable signal-timing adjustment recommendations for city traffic engineers. Format your response in clean, professional markdown."; - - const response = await fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - contents: [{ - parts: [{ - text: `${systemInstruction}\n\nUser Question/Prompt: ${prompt}\n\nHere is the active traffic telemetry data context:\n${JSON.stringify(dataContext, null, 2)}` - }] - }] - }) - }); - - if (!response.ok) { - const errBody = await response.text(); - throw new Error(`Gemini API returned status ${response.status}: ${errBody}`); - } - - const data = await response.json(); - const geminiText = data.candidates?.[0]?.content?.parts?.[0]?.text || 'No response returned from Gemini API.'; - res.json({ response: geminiText }); - - } catch (error) { - console.error('Error invoking Gemini API:', error); - res.status(500).json({ message: 'Error processing AI insights with Gemini API', details: error.message }); + + // Add a slight artificial delay to feel like a real network AI response + await new Promise((r) => setTimeout(r, 1200)); + return res.json({ response: mockResponse }); + } + + try { + const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`; + const systemInstruction = + "You are TraffiTech's Gemini Enterprise Traffic Advisor. You analyze urban traffic telemetry data (corridors, bottlenecks, speeds, risks, signal tuning) and provide detailed, structured diagnostic reports and actionable signal-timing adjustment recommendations for city traffic engineers. Format your response in clean, professional markdown."; + + const response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + contents: [ + { + parts: [ + { + text: `${systemInstruction}\n\nUser Question/Prompt: ${prompt}\n\nHere is the active traffic telemetry data context:\n${JSON.stringify(dataContext, null, 2)}`, + }, + ], + }, + ], + }), + }); + + if (!response.ok) { + const errBody = await response.text(); + throw new Error(`Gemini API returned status ${response.status}: ${errBody}`); } + + const data = await response.json(); + const geminiText = + data.candidates?.[0]?.content?.parts?.[0]?.text || 'No response returned from Gemini API.'; + res.json({ response: geminiText }); + } catch (error) { + console.error('Error invoking Gemini API:', error); + res + .status(500) + .json({ message: 'Error processing AI insights with Gemini API', details: error.message }); + } }); module.exports = router; diff --git a/server/routes/webhooks.js b/server/routes/webhooks.js index 4e52528..5c3e6ec 100644 --- a/server/routes/webhooks.js +++ b/server/routes/webhooks.js @@ -6,37 +6,37 @@ const Booking = require('../models/Booking'); // Stripe Webhook Endpoint // Note: This requires the stripe CLI or a public URL to test locally router.post('/', express.raw({ type: 'application/json' }), async (req, res) => { - const sig = req.headers['stripe-signature']; - let event; + const sig = req.headers['stripe-signature']; + let event; - try { - event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET); - } catch (err) { - return res.status(400).send(`Webhook Error: ${err.message}`); - } + try { + event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET); + } catch (err) { + return res.status(400).send(`Webhook Error: ${err.message}`); + } - // Handle the event - if (event.type === 'payment_intent.succeeded') { - const paymentIntent = event.data.object; - console.log(`💰 PaymentIntent for ${paymentIntent.amount} was successful!`); + // Handle the event + if (event.type === 'payment_intent.succeeded') { + const paymentIntent = event.data.object; + console.log(`💰 PaymentIntent for ${paymentIntent.amount} was successful!`); - // Update booking status if metadata exists - const bookingId = paymentIntent.metadata.bookingId; - if (bookingId) { - try { - const booking = await Booking.findById(bookingId); - if (booking) { - booking.paymentStatus = 'paid'; - booking.paymentId = paymentIntent.id; // Record transaction ID for refunds - await booking.save(); - } - } catch (err) { - console.error('Error updating booking via webhook:', err); - } + // Update booking status if metadata exists + const bookingId = paymentIntent.metadata.bookingId; + if (bookingId) { + try { + const booking = await Booking.findById(bookingId); + if (booking) { + booking.paymentStatus = 'paid'; + booking.paymentId = paymentIntent.id; // Record transaction ID for refunds + await booking.save(); } + } catch (err) { + console.error('Error updating booking via webhook:', err); + } } + } - res.json({ received: true }); + res.json({ received: true }); }); module.exports = router; diff --git a/server/utils/SimulationService.js b/server/utils/SimulationService.js index 5c7f5b0..654d424 100644 --- a/server/utils/SimulationService.js +++ b/server/utils/SimulationService.js @@ -1,41 +1,41 @@ class SimulationService { - constructor(io) { - this.io = io; - this.interval = null; - this.isRunning = false; - } + constructor(io) { + this.io = io; + this.interval = null; + this.isRunning = false; + } - start() { - if (this.isRunning) return; - this.isRunning = true; + start() { + if (this.isRunning) return; + this.isRunning = true; - this.interval = setInterval(() => { - const sensorData = { - timestamp: new Date().toISOString(), - parking: { - totalSlots: 150, - occupied: Math.floor(Math.random() * 50) + 80, - status: 'active' - }, - traffic: { - congestionLevel: Math.floor(Math.random() * 100), - avgSpeed: Math.floor(Math.random() * 20) + 30, - status: 'monitoring' - } - }; - this.io.emit('iot_update', sensorData); - }, 5000); + this.interval = setInterval(() => { + const sensorData = { + timestamp: new Date().toISOString(), + parking: { + totalSlots: 150, + occupied: Math.floor(Math.random() * 50) + 80, + status: 'active', + }, + traffic: { + congestionLevel: Math.floor(Math.random() * 100), + avgSpeed: Math.floor(Math.random() * 20) + 30, + status: 'monitoring', + }, + }; + this.io.emit('iot_update', sensorData); + }, 5000); - console.log('📡 IoT Simulation Service Started'); - } + console.log('📡 IoT Simulation Service Started'); + } - stop() { - if (this.interval) { - clearInterval(this.interval); - this.isRunning = false; - console.log('🛑 IoT Simulation Service Stopped'); - } + stop() { + if (this.interval) { + clearInterval(this.interval); + this.isRunning = false; + console.log('🛑 IoT Simulation Service Stopped'); } + } } module.exports = SimulationService; diff --git a/server/utils/jsonDB.js b/server/utils/jsonDB.js index b4146d1..d1e7754 100644 --- a/server/utils/jsonDB.js +++ b/server/utils/jsonDB.js @@ -2,98 +2,101 @@ const fs = require('fs'); const path = require('path'); class JsonDB { - constructor(collectionName) { - this.filePath = path.join(__dirname, '../data', `${collectionName}.json`); - this.ensureFileExists(); - this.lockQueue = Promise.resolve(); - } + constructor(collectionName) { + this.filePath = path.join(__dirname, '../data', `${collectionName}.json`); + this.ensureFileExists(); + this.lockQueue = Promise.resolve(); + } - ensureFileExists() { - const dir = path.dirname(this.filePath); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - if (!fs.existsSync(this.filePath)) { - fs.writeFileSync(this.filePath, JSON.stringify([])); - } + ensureFileExists() { + const dir = path.dirname(this.filePath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); } - - // Execute any function sequentially inside a mutex lock queue - lock(fn) { - const next = this.lockQueue.then(async () => { - return await fn(); - }); - this.lockQueue = next.catch(() => {}); - return next; + if (!fs.existsSync(this.filePath)) { + fs.writeFileSync(this.filePath, JSON.stringify([])); } + } - async read() { - return this.lock(async () => { - const data = fs.readFileSync(this.filePath, 'utf8'); - return JSON.parse(data); - }); - } + // Execute any function sequentially inside a mutex lock queue + lock(fn) { + const next = this.lockQueue.then(async () => { + return await fn(); + }); + this.lockQueue = next.catch(() => {}); + return next; + } - async write(data) { - return this.lock(async () => { - fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2)); - }); - } + async read() { + return this.lock(async () => { + const data = fs.readFileSync(this.filePath, 'utf8'); + return JSON.parse(data); + }); + } - async find(query = {}) { - return this.lock(async () => { - const raw = fs.readFileSync(this.filePath, 'utf8'); - const data = JSON.parse(raw); - return data.filter(item => { - for (let key in query) { - if (item[key] !== query[key]) return false; - } - return true; - }); - }); - } + async write(data) { + return this.lock(async () => { + fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2)); + }); + } - async findOne(query = {}) { - return this.lock(async () => { - const raw = fs.readFileSync(this.filePath, 'utf8'); - const data = JSON.parse(raw); - return data.find(item => { - for (let key in query) { - if (item[key] !== query[key]) return false; - } - return true; - }); - }); - } + async find(query = {}) { + return this.lock(async () => { + const raw = fs.readFileSync(this.filePath, 'utf8'); + const data = JSON.parse(raw); + return data.filter((item) => { + for (const key in query) { + if (item[key] !== query[key]) return false; + } + return true; + }); + }); + } - async create(item) { - return this.lock(async () => { - const raw = fs.readFileSync(this.filePath, 'utf8'); - const data = JSON.parse(raw); - const newItem = { ...item, _id: Date.now().toString() + Math.random().toString(36).substring(2, 6) }; - data.push(newItem); - fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2)); - return newItem; - }); - } + async findOne(query = {}) { + return this.lock(async () => { + const raw = fs.readFileSync(this.filePath, 'utf8'); + const data = JSON.parse(raw); + return data.find((item) => { + for (const key in query) { + if (item[key] !== query[key]) return false; + } + return true; + }); + }); + } - async update(id, item) { - return this.lock(async () => { - const raw = fs.readFileSync(this.filePath, 'utf8'); - const data = JSON.parse(raw); - const index = data.findIndex(x => x._id === id); - if (index !== -1) { - data[index] = { ...data[index], ...item }; - fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2)); - return data[index]; - } - return null; - }); - } + async create(item) { + return this.lock(async () => { + const raw = fs.readFileSync(this.filePath, 'utf8'); + const data = JSON.parse(raw); + const newItem = { + ...item, + _id: Date.now().toString() + Math.random().toString(36).substring(2, 6), + }; + data.push(newItem); + fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2)); + return newItem; + }); + } - async findById(id) { - return this.findOne({ _id: id }); - } + async update(id, item) { + return this.lock(async () => { + const raw = fs.readFileSync(this.filePath, 'utf8'); + const data = JSON.parse(raw); + const index = data.findIndex((x) => x._id === id); + if (index !== -1) { + data[index] = { ...data[index], ...item }; + fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2)); + return data[index]; + } + return null; + }); + } + + async findById(id) { + return this.findOne({ _id: id }); + } } module.exports = JsonDB; diff --git a/src/App.jsx b/src/App.jsx index dc196c5..098aff2 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -18,7 +18,9 @@ import { NotificationProvider } from './components/notifications/NotificationSys import { loadStripe } from '@stripe/stripe-js'; import { Elements } from '@stripe/react-stripe-js'; -const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_test_TYooMQauvdEDq54NiTphI7jx'); +const stripePromise = loadStripe( + import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_test_TYooMQauvdEDq54NiTphI7jx' +); const parseJwt = (token) => { try { @@ -27,11 +29,17 @@ const parseJwt = (token) => { if (parts.length !== 3) return null; const base64Url = parts[1]; const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); - const jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) { - return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); - }).join('')); + const jsonPayload = decodeURIComponent( + window + .atob(base64) + .split('') + .map(function (c) { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); + }) + .join('') + ); return JSON.parse(jsonPayload); - } catch (_err) { + } catch { return null; } }; @@ -72,22 +80,74 @@ function App() { } /> } /> - - - - }> + + + + } + > } /> - } /> - } /> + + + + } + /> + + + + } + /> } /> } /> - } /> - } /> - } /> + + + + } + /> + + + + } + /> + + + + } + /> } /> - } /> - } /> + + + + } + /> + + + + } + /> } /> diff --git a/src/__tests__/ParkingCard.test.jsx b/src/__tests__/ParkingCard.test.jsx index 49e26da..8151710 100644 --- a/src/__tests__/ParkingCard.test.jsx +++ b/src/__tests__/ParkingCard.test.jsx @@ -28,7 +28,14 @@ function ParkingCard({ zone, basePrice, availableSpots, currentHour }) { describe('ParkingCard', () => { it('displays the correct zone name', () => { - render(); + render( + + ); expect(screen.getByTestId('zone-name')).toHaveTextContent('Zone A — Central Hub'); }); diff --git a/src/components/ThemeContext.jsx b/src/components/ThemeContext.jsx index 200f2d3..05500b7 100644 --- a/src/components/ThemeContext.jsx +++ b/src/components/ThemeContext.jsx @@ -3,31 +3,27 @@ import React, { createContext, useContext, useEffect, useState } from 'react'; const ThemeContext = createContext(); export const ThemeProvider = ({ children }) => { - // Default to 'light' since that's what was recently applied - const [theme, setTheme] = useState(localStorage.getItem('theme') || 'light'); + // Default to 'light' since that's what was recently applied + const [theme, setTheme] = useState(localStorage.getItem('theme') || 'light'); - useEffect(() => { - const root = window.document.documentElement; - const body = window.document.body; + useEffect(() => { + const root = window.document.documentElement; + const body = window.document.body; - root.classList.remove('light', 'dark'); - body.classList.remove('light', 'dark'); + root.classList.remove('light', 'dark'); + body.classList.remove('light', 'dark'); - root.classList.add(theme); - body.classList.add(theme); // Necessary for body-level CSS overrides + root.classList.add(theme); + body.classList.add(theme); // Necessary for body-level CSS overrides - localStorage.setItem('theme', theme); - }, [theme]); + localStorage.setItem('theme', theme); + }, [theme]); - const toggleTheme = () => { - setTheme(prev => prev === 'light' ? 'dark' : 'light'); - }; + const toggleTheme = () => { + setTheme((prev) => (prev === 'light' ? 'dark' : 'light')); + }; - return ( - - {children} - - ); + return {children}; }; export const useTheme = () => useContext(ThemeContext); diff --git a/src/components/layout/DashboardLayout.jsx b/src/components/layout/DashboardLayout.jsx index 6b3244a..1bd38f4 100644 --- a/src/components/layout/DashboardLayout.jsx +++ b/src/components/layout/DashboardLayout.jsx @@ -6,34 +6,38 @@ import { useTheme } from '../ThemeContext'; import { Sun, Moon } from 'lucide-react'; const DashboardLayout = () => { - const { theme, toggleTheme } = useTheme(); + const { theme, toggleTheme } = useTheme(); - return ( -
- -
-
-
- {/* Background Ambient Glow */} -
-
+ return ( +
+ +
+
+
+ {/* Background Ambient Glow */} +
+
-
- -
+
+ +
- {/* Floating Global Theme Toggle */} - -
-
-
- ); + {/* Floating Global Theme Toggle */} + +
+
+
+ ); }; export default DashboardLayout; diff --git a/src/components/layout/Header.jsx b/src/components/layout/Header.jsx index 6e02540..45a1e20 100644 --- a/src/components/layout/Header.jsx +++ b/src/components/layout/Header.jsx @@ -3,67 +3,66 @@ import { useTheme } from '../ThemeContext'; import { useApp } from '../../context/AppContext'; const Header = () => { - const { theme, toggleTheme } = useTheme(); - const { toggleMobileMenu } = useApp(); + const { theme, toggleTheme } = useTheme(); + const { toggleMobileMenu } = useApp(); - return ( -
-
- {/* Mobile Menu Toggle */} - + return ( +
+
+ {/* Mobile Menu Toggle */} + - {/* Search Bar (Hidden on mobile searching, or simplified) */} -
- - -
-
- - {/* Right Actions */} -
- {/* Theme Toggle */} - + {/* Search Bar (Hidden on mobile searching, or simplified) */} +
+ + +
+
+ {/* Right Actions */} +
+ {/* Theme Toggle */} + - {/* Notifications */} - + {/* Notifications */} + - {/* Profile */} -
-
-
- -

Admin Control

-
-

Chief Operator (Secured)

-
-
-
- -
-
-
+ {/* Profile */} +
+
+
+ +

Admin Control

+
+

Chief Operator (Secured)

+
+
+
+
-
- ); +
+ + +
+ ); }; export default Header; diff --git a/src/components/layout/Sidebar.jsx b/src/components/layout/Sidebar.jsx index 3e5cb9f..ac1ede8 100644 --- a/src/components/layout/Sidebar.jsx +++ b/src/components/layout/Sidebar.jsx @@ -1,5 +1,20 @@ import React from 'react'; -import { LayoutDashboard, Car, CircleParking, BarChart3, Settings, ShieldAlert, History, PieChart, LogOut, User as UserIcon, X, Cpu, Eye, Smartphone } from 'lucide-react'; +import { + LayoutDashboard, + Car, + CircleParking, + BarChart3, + Settings, + ShieldAlert, + History, + PieChart, + LogOut, + User as UserIcon, + X, + Cpu, + Eye, + Smartphone, +} from 'lucide-react'; import { NavLink, useNavigate } from 'react-router-dom'; import { clsx } from 'clsx'; import { motion, AnimatePresence } from 'framer-motion'; @@ -7,161 +22,180 @@ import { authAPI } from '../../services/api'; import { useApp } from '../../context/AppContext'; const Sidebar = () => { - const navigate = useNavigate(); - const { isMobileMenuOpen, closeMobileMenu } = useApp(); - const user = JSON.parse(localStorage.getItem('user') || '{}'); + const navigate = useNavigate(); + const { isMobileMenuOpen, closeMobileMenu } = useApp(); + const user = JSON.parse(localStorage.getItem('user') || '{}'); - const handleLogout = () => { - authAPI.logout(); - navigate('/login'); - }; - const navItems = [ - { icon: LayoutDashboard, label: 'Overview', path: '/' }, - { icon: CircleParking, label: 'Smart Parking', path: '/parking' }, - { icon: Smartphone, label: 'Citizen Portal', path: '/citizen-portal' }, - { icon: History, label: 'Booking History', path: '/booking-history' }, - { icon: Car, label: 'Traffic Control', path: '/traffic', adminOnly: true }, - { icon: Eye, label: 'Computer Vision', path: '/traffic-cv', adminOnly: true }, - { icon: BarChart3, label: 'Analytics', path: '/analytics', adminOnly: true }, - { icon: Cpu, label: 'RAPIDS Analytics', path: '/rapids-analytics', adminOnly: true }, - { icon: PieChart, label: 'Parking Analytics', path: '/parking-analytics', adminOnly: true }, - { icon: Settings, label: 'Settings', path: '/settings', adminOnly: true }, - { icon: ShieldAlert, label: 'User Admin', path: '/admin-users', adminOnly: true }, - ]; + const handleLogout = () => { + authAPI.logout(); + navigate('/login'); + }; + const navItems = [ + { icon: LayoutDashboard, label: 'Overview', path: '/' }, + { icon: CircleParking, label: 'Smart Parking', path: '/parking' }, + { icon: Smartphone, label: 'Citizen Portal', path: '/citizen-portal' }, + { icon: History, label: 'Booking History', path: '/booking-history' }, + { icon: Car, label: 'Traffic Control', path: '/traffic', adminOnly: true }, + { icon: Eye, label: 'Computer Vision', path: '/traffic-cv', adminOnly: true }, + { icon: BarChart3, label: 'Analytics', path: '/analytics', adminOnly: true }, + { icon: Cpu, label: 'RAPIDS Analytics', path: '/rapids-analytics', adminOnly: true }, + { icon: PieChart, label: 'Parking Analytics', path: '/parking-analytics', adminOnly: true }, + { icon: Settings, label: 'Settings', path: '/settings', adminOnly: true }, + { icon: ShieldAlert, label: 'User Admin', path: '/admin-users', adminOnly: true }, + ]; - const filteredNavItems = navItems.filter(item => !item.adminOnly || user.role === 'admin'); + const filteredNavItems = navItems.filter((item) => !item.adminOnly || user.role === 'admin'); + return ( + <> + {/* Mobile Overlay */} + + {isMobileMenuOpen && ( + + )} + - return ( - <> - {/* Mobile Overlay */} - - {isMobileMenuOpen && ( + - - ); +
+

+ System Status +

+
+ + + + + + ONLINE + +
+
+
+

+ Encrypted Session +

+
+ + +
+
+ + + + ); }; export default Sidebar; diff --git a/src/components/notifications/NotificationSystem.jsx b/src/components/notifications/NotificationSystem.jsx index 4151f8c..9adbb28 100644 --- a/src/components/notifications/NotificationSystem.jsx +++ b/src/components/notifications/NotificationSystem.jsx @@ -5,138 +5,157 @@ import { X, CheckCircle2, AlertCircle, Info, AlertTriangle } from 'lucide-react' const NotificationContext = createContext(); export const useNotifications = () => { - const context = useContext(NotificationContext); - if (!context) { - throw new Error('useNotifications must be used within NotificationProvider'); - } - return context; + const context = useContext(NotificationContext); + if (!context) { + throw new Error('useNotifications must be used within NotificationProvider'); + } + return context; }; export const NotificationProvider = ({ children }) => { - const [notifications, setNotifications] = useState([]); - - const addNotification = useCallback((notification) => { - const id = Date.now(); - const newNotification = { - id, - type: notification.type || 'info', - title: notification.title, - message: notification.message, - duration: notification.duration || 5000, - }; - - setNotifications(prev => [...prev, newNotification]); - - // Auto remove after duration - if (newNotification.duration > 0) { - setTimeout(() => { - removeNotification(id); - }, newNotification.duration); - } - - return id; - }, []); - - const removeNotification = useCallback((id) => { - setNotifications(prev => prev.filter(n => n.id !== id)); - }, []); - - const success = useCallback((title, message) => { - return addNotification({ type: 'success', title, message }); - }, [addNotification]); - - const error = useCallback((title, message) => { - return addNotification({ type: 'error', title, message }); - }, [addNotification]); - - const warning = useCallback((title, message) => { - return addNotification({ type: 'warning', title, message }); - }, [addNotification]); - - const info = useCallback((title, message) => { - return addNotification({ type: 'info', title, message }); - }, [addNotification]); - - return ( - - {children} - - - ); + const [notifications, setNotifications] = useState([]); + + const removeNotification = useCallback((id) => { + setNotifications((prev) => prev.filter((n) => n.id !== id)); + }, []); + + const addNotification = useCallback( + (notification) => { + const id = Date.now(); + const newNotification = { + id, + type: notification.type || 'info', + title: notification.title, + message: notification.message, + duration: notification.duration || 5000, + }; + + setNotifications((prev) => [...prev, newNotification]); + + // Auto remove after duration + if (newNotification.duration > 0) { + setTimeout(() => { + removeNotification(id); + }, newNotification.duration); + } + + return id; + }, + [removeNotification] + ); + + const success = useCallback( + (title, message) => { + return addNotification({ type: 'success', title, message }); + }, + [addNotification] + ); + + const error = useCallback( + (title, message) => { + return addNotification({ type: 'error', title, message }); + }, + [addNotification] + ); + + const warning = useCallback( + (title, message) => { + return addNotification({ type: 'warning', title, message }); + }, + [addNotification] + ); + + const info = useCallback( + (title, message) => { + return addNotification({ type: 'info', title, message }); + }, + [addNotification] + ); + + return ( + + {children} + + + ); }; const NotificationContainer = ({ notifications, onRemove }) => { - return ( -
- - {notifications.map((notification) => ( - onRemove(notification.id)} - /> - ))} - -
- ); + return ( +
+ + {notifications.map((notification) => ( + onRemove(notification.id)} + /> + ))} + +
+ ); }; const Notification = ({ notification, onClose }) => { - const config = { - success: { - icon: CheckCircle2, - color: 'brand-green', - bg: 'bg-brand-green/10', - border: 'border-brand-green/30' - }, - error: { - icon: AlertCircle, - color: 'brand-red', - bg: 'bg-brand-red/10', - border: 'border-brand-red/30' - }, - warning: { - icon: AlertTriangle, - color: 'brand-yellow', - bg: 'bg-brand-yellow/10', - border: 'border-brand-yellow/30' - }, - info: { - icon: Info, - color: 'brand-blue', - bg: 'bg-brand-blue/10', - border: 'border-brand-blue/30' - } - }; - - const { icon: Icon, color, bg, border } = config[notification.type] || config.info; - - return ( - +
+
+ +
+
+

+ {notification.title} +

+ {notification.message && ( +

{notification.message}

+ )} +
+ -
-
- ); + + + + + ); }; export default NotificationProvider; diff --git a/src/components/parking/BookingHistory.jsx b/src/components/parking/BookingHistory.jsx index 110888b..8b0bccf 100644 --- a/src/components/parking/BookingHistory.jsx +++ b/src/components/parking/BookingHistory.jsx @@ -1,232 +1,279 @@ import React, { useState, useEffect } from 'react'; -import { History, Calendar, MapPin, Clock, Car, DollarSign, X, ChevronRight, Loader2, AlertCircle } from 'lucide-react'; +import { + History, + Calendar, + MapPin, + Clock, + Car, + DollarSign, + X, + ChevronRight, + Loader2, + AlertCircle, +} from 'lucide-react'; import { motion } from 'framer-motion'; import { clsx } from 'clsx'; import { bookingAPI } from '../../services/api'; const BookingHistory = () => { - const [bookings, setBookings] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(''); - const [filter, setFilter] = useState('all'); // all, upcoming, completed, cancelled - - const fetchBookings = async () => { - try { - setLoading(true); - setError(''); - const data = await bookingAPI.getAll(); - setBookings(data); - } catch (err) { - setError(err.message || 'Failed to fetch bookings'); - } finally { - setLoading(false); - } - }; - - useEffect(() => { - fetchBookings(); - }, []); - - const getBookingStatus = (booking) => { - const bookingDateTime = new Date(`${booking.date}T${booking.startTime}`); - const now = new Date(); - - if (booking.cancelled || booking.paymentStatus === 'cancelled' || booking.paymentStatus === 'refunded') return 'cancelled'; - if (bookingDateTime > now) return 'upcoming'; - return 'completed'; - }; - - const filteredBookings = bookings.filter(booking => { - if (filter === 'all') return true; - return getBookingStatus(booking) === filter; - }); - - const handleCancel = async (booking) => { - if (!window.confirm("Are you sure you want to cancel this booking and request a refund?")) return; - try { - const id = booking._id || booking.id; - await bookingAPI.cancel(id); - setBookings(prev => prev.map(b => - (b._id === id || b.bookingId === booking.bookingId) - ? { ...b, paymentStatus: 'refunded', cancelled: true } - : b - )); - } catch (err) { - console.error("Cancellation Error:", err); - setError(err.message || 'Failed to cancel booking'); - } - }; - - const statusConfig = { - upcoming: { color: 'brand-blue', label: 'Upcoming', bg: 'bg-brand-blue/10', border: 'border-brand-blue/20' }, - completed: { color: 'brand-green', label: 'Completed', bg: 'bg-brand-green/10', border: 'border-brand-green/20' }, - cancelled: { color: 'brand-red', label: 'Cancelled', bg: 'bg-brand-red/10', border: 'border-brand-red/20' } - }; - - return ( -
-
-
-
- + const [bookings, setBookings] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [filter, setFilter] = useState('all'); // all, upcoming, completed, cancelled + + const fetchBookings = async () => { + try { + setLoading(true); + setError(''); + const data = await bookingAPI.getAll(); + setBookings(data); + } catch (err) { + setError(err.message || 'Failed to fetch bookings'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchBookings(); + }, []); + + const getBookingStatus = (booking) => { + const bookingDateTime = new Date(`${booking.date}T${booking.startTime}`); + const now = new Date(); + + if ( + booking.cancelled || + booking.paymentStatus === 'cancelled' || + booking.paymentStatus === 'refunded' + ) + return 'cancelled'; + if (bookingDateTime > now) return 'upcoming'; + return 'completed'; + }; + + const filteredBookings = bookings.filter((booking) => { + if (filter === 'all') return true; + return getBookingStatus(booking) === filter; + }); + + const handleCancel = async (booking) => { + if (!window.confirm('Are you sure you want to cancel this booking and request a refund?')) + return; + try { + const id = booking._id || booking.id; + await bookingAPI.cancel(id); + setBookings((prev) => + prev.map((b) => + b._id === id || b.bookingId === booking.bookingId + ? { ...b, paymentStatus: 'refunded', cancelled: true } + : b + ) + ); + } catch (err) { + console.error('Cancellation Error:', err); + setError(err.message || 'Failed to cancel booking'); + } + }; + + const statusConfig = { + upcoming: { + color: 'brand-blue', + label: 'Upcoming', + bg: 'bg-brand-blue/10', + border: 'border-brand-blue/20', + }, + completed: { + color: 'brand-green', + label: 'Completed', + bg: 'bg-brand-green/10', + border: 'border-brand-green/20', + }, + cancelled: { + color: 'brand-red', + label: 'Cancelled', + bg: 'bg-brand-red/10', + border: 'border-brand-red/20', + }, + }; + + return ( +
+
+
+
+ +
+
+

Booking History

+

+ {bookings.length} total bookings +

+
+
+
+ + {/* Filter Tabs */} +
+ {[ + { value: 'all', label: 'All Bookings' }, + { value: 'upcoming', label: 'Upcoming' }, + { value: 'completed', label: 'Completed' }, + { value: 'cancelled', label: 'Cancelled' }, + ].map((tab) => ( + + ))} +
+ + {/* Bookings List */} + {loading ? ( +
+ +

+ Fetching your bookings... +

+
+ ) : error ? ( +
+ +

{error}

+ +
+ ) : filteredBookings.length === 0 ? ( +
+ +

No bookings found

+

+ Your booking history will appear here +

+
+ ) : ( +
+ {filteredBookings.reverse().map((booking, index) => { + const status = getBookingStatus(booking); + const config = statusConfig[status]; + + return ( + +
+
+
+
-

Booking History

-

{bookings.length} total bookings

+

+ {booking.parkingZone?.label || 'Parking Zone'} +

+

+ Booking ID: {booking.bookingId} +

+
+ + {config.label} +
-
- - {/* Filter Tabs */} -
- {[ - { value: 'all', label: 'All Bookings' }, - { value: 'upcoming', label: 'Upcoming' }, - { value: 'completed', label: 'Completed' }, - { value: 'cancelled', label: 'Cancelled' } - ].map((tab) => ( - - ))} -
- - {/* Bookings List */} - {loading ? ( -
- -

Fetching your bookings...

+ +
+
+

+ + Slot +

+

+ {booking.slot?.title} +

+
+
+

+ + Date +

+

+ {new Date(booking.date).toLocaleDateString()} +

+
+
+

+ + Time +

+

+ {booking.startTime} - {booking.endTime} +

+
+
+

+ + Vehicle +

+

+ {booking.vehicleNumber} +

+
- ) : error ? ( -
- -

{error}

+ +
+
+ + ₹{booking.totalPrice?.toFixed(0)} + + + ({booking.duration}h) + +
+ + {status === 'upcoming' && !booking.cancelled && ( + )} + + {status === 'completed' && ( + + )}
- ) : filteredBookings.length === 0 ? ( -
- -

No bookings found

-

Your booking history will appear here

-
- ) : ( -
- {filteredBookings.reverse().map((booking, index) => { - const status = getBookingStatus(booking); - const config = statusConfig[status]; - - return ( - -
-
-
- -
-
-

{booking.parkingZone?.label || 'Parking Zone'}

-

Booking ID: {booking.bookingId}

-
-
- - {config.label} - -
- -
-
-

- - Slot -

-

{booking.slot?.title}

-
-
-

- - Date -

-

- {new Date(booking.date).toLocaleDateString()} -

-
-
-

- - Time -

-

- {booking.startTime} - {booking.endTime} -

-
-
-

- - Vehicle -

-

{booking.vehicleNumber}

-
-
- -
-
- - ₹{booking.totalPrice?.toFixed(0)} - - - ({booking.duration}h) - -
- - {status === 'upcoming' && !booking.cancelled && ( - - )} - - {status === 'completed' && ( - - )} -
-
- ); - })} -
- )} + + ); + })}
- ); + )} +
+ ); }; export default BookingHistory; diff --git a/src/components/parking/BookingModal.jsx b/src/components/parking/BookingModal.jsx index 85ada37..da32557 100644 --- a/src/components/parking/BookingModal.jsx +++ b/src/components/parking/BookingModal.jsx @@ -4,334 +4,381 @@ import { motion, AnimatePresence } from 'framer-motion'; import { clsx } from 'clsx'; const BookingModal = ({ slot, parkingZone, onClose, onConfirm }) => { - const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]); - const [selectedTime, setSelectedTime] = useState('14:00'); - const [duration, setDuration] = useState(2); // hours - const [vehicleNumber, setVehicleNumber] = useState('KA-01-AB-1234'); - const [vehicleType, setVehicleType] = useState('car'); - const [step, setStep] = useState(1); // 1: Details, 2: Confirmation + const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]); + const [selectedTime, setSelectedTime] = useState('14:00'); + const [duration, setDuration] = useState(2); // hours + const [vehicleNumber, setVehicleNumber] = useState('KA-01-AB-1234'); + const [vehicleType, setVehicleType] = useState('car'); + const [step, setStep] = useState(1); // 1: Details, 2: Confirmation - const timeSlots = [ - '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', - '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00' - ]; + const timeSlots = [ + '08:00', + '09:00', + '10:00', + '11:00', + '12:00', + '13:00', + '14:00', + '15:00', + '16:00', + '17:00', + '18:00', + '19:00', + '20:00', + ]; - const durations = [ - { value: 1, label: '1 Hour', price: parkingZone?.price || 50 }, - { value: 2, label: '2 Hours', price: (parkingZone?.price || 50) * 2 }, - { value: 4, label: '4 Hours', price: (parkingZone?.price || 50) * 4 }, - { value: 8, label: 'Full Day', price: (parkingZone?.price || 50) * 8 * 0.9 }, // 10% discount - ]; + const durations = [ + { value: 1, label: '1 Hour', price: parkingZone?.price || 50 }, + { value: 2, label: '2 Hours', price: (parkingZone?.price || 50) * 2 }, + { value: 4, label: '4 Hours', price: (parkingZone?.price || 50) * 4 }, + { value: 8, label: 'Full Day', price: (parkingZone?.price || 50) * 8 * 0.9 }, // 10% discount + ]; - const vehicleTypes = [ - { value: 'car', label: 'Car', icon: '🚗' }, - { value: 'suv', label: 'SUV', icon: '🚙' }, - { value: 'bike', label: 'Motorcycle', icon: '🏍️' }, - { value: 'ev', label: 'Electric', icon: '⚡' }, - ]; + const vehicleTypes = [ + { value: 'car', label: 'Car', icon: '🚗' }, + { value: 'suv', label: 'SUV', icon: '🚙' }, + { value: 'bike', label: 'Motorcycle', icon: '🏍️' }, + { value: 'ev', label: 'Electric', icon: '⚡' }, + ]; - const calculateEndTime = () => { - const [hours, minutes] = selectedTime.split(':'); - const endHour = (parseInt(hours) + duration) % 24; - return `${endHour.toString().padStart(2, '0')}:${minutes}`; - }; + const calculateEndTime = () => { + const [hours, minutes] = selectedTime.split(':'); + const endHour = (parseInt(hours) + duration) % 24; + return `${endHour.toString().padStart(2, '0')}:${minutes}`; + }; - const totalPrice = durations.find(d => d.value === duration)?.price || 0; + const totalPrice = durations.find((d) => d.value === duration)?.price || 0; - const handleNext = () => { - if (!vehicleNumber.trim()) { - alert('Please enter vehicle number'); - return; - } - setStep(2); - }; + const handleNext = () => { + if (!vehicleNumber.trim()) { + alert('Please enter vehicle number'); + return; + } + setStep(2); + }; - const handleConfirm = () => { - const booking = { - slot: slot, - parkingZone: parkingZone, - date: selectedDate, - startTime: selectedTime, - endTime: calculateEndTime(), - duration: duration, - vehicleNumber: vehicleNumber, - vehicleType: vehicleType, - totalPrice: totalPrice, - bookingId: `BK${Date.now()}`, - timestamp: new Date().toISOString() - }; + const handleConfirm = () => { + const booking = { + slot: slot, + parkingZone: parkingZone, + date: selectedDate, + startTime: selectedTime, + endTime: calculateEndTime(), + duration: duration, + vehicleNumber: vehicleNumber, + vehicleType: vehicleType, + totalPrice: totalPrice, + bookingId: `BK${Date.now()}`, + timestamp: new Date().toISOString(), + }; - // Save to localStorage - const existingBookings = JSON.parse(localStorage.getItem('parkingBookings') || '[]'); - existingBookings.push(booking); - localStorage.setItem('parkingBookings', JSON.stringify(existingBookings)); + // Save to localStorage + const existingBookings = JSON.parse(localStorage.getItem('parkingBookings') || '[]'); + existingBookings.push(booking); + localStorage.setItem('parkingBookings', JSON.stringify(existingBookings)); - onConfirm(booking); - onClose(); - }; + onConfirm(booking); + onClose(); + }; - return ( - - + + e.stopPropagation()} + className="glass-panel rounded-2xl p-6 max-w-2xl w-full max-h-[90vh] overflow-y-auto custom-scrollbar" + > + {/* Header */} +
+
+
+ +
+
+

+ {step === 1 ? 'Book Parking Slot' : 'Confirm Booking'} +

+

+ {parkingZone?.label || 'Parking Zone'} • Slot {slot?.title} +

+
+
+ -
+ + +
- {step === 1 ? ( -
- {/* Date Selection */} -
- - setSelectedDate(e.target.value)} - min={new Date().toISOString().split('T')[0]} - className="w-full px-4 py-3 bg-white shadow-sm border border-slate-200 dark:border-white/10 dark:bg-white/5 dark:border-white/10 border rounded-xl text-slate-800 dark:text-white focus:border-brand-blue focus:outline-none transition-colors" - /> -
+ {step === 1 ? ( +
+ {/* Date Selection */} +
+ + setSelectedDate(e.target.value)} + min={new Date().toISOString().split('T')[0]} + className="w-full px-4 py-3 bg-white shadow-sm border border-slate-200 dark:border-white/10 dark:bg-white/5 dark:border-white/10 border rounded-xl text-slate-800 dark:text-white focus:border-brand-blue focus:outline-none transition-colors" + /> +
- {/* Time Slot Selection */} -
- -
- {timeSlots.map((time) => ( - - ))} -
-
+ {/* Time Slot Selection */} +
+ +
+ {timeSlots.map((time) => ( + + ))} +
+
- {/* Duration Selection */} -
- -
- {durations.map((d) => ( - - ))} -
-
+ {/* Duration Selection */} +
+ +
+ {durations.map((d) => ( + + ))} +
+
- {/* Vehicle Type */} -
- -
- {vehicleTypes.map((type) => ( - - ))} -
-
+ {/* Vehicle Type */} +
+ +
+ {vehicleTypes.map((type) => ( + + ))} +
+
- {/* Vehicle Number */} -
- -
- - setVehicleNumber(e.target.value.toUpperCase())} - placeholder="e.g., KA-01-AB-1234" - className="w-full pl-12 pr-4 py-3 bg-white shadow-sm border border-slate-200 dark:border-white/10 dark:bg-white/5 dark:border-white/10 border rounded-xl text-slate-800 dark:text-white placeholder-slate-500 focus:border-brand-blue focus:outline-none transition-colors uppercase" - /> -
-
+ {/* Vehicle Number */} +
+ +
+ + setVehicleNumber(e.target.value.toUpperCase())} + placeholder="e.g., KA-01-AB-1234" + className="w-full pl-12 pr-4 py-3 bg-white shadow-sm border border-slate-200 dark:border-white/10 dark:bg-white/5 dark:border-white/10 border rounded-xl text-slate-800 dark:text-white placeholder-slate-500 focus:border-brand-blue focus:outline-none transition-colors uppercase" + /> +
+
- {/* Summary */} -
-

- Booking Summary -

-
-
- Date & Time: - - {new Date(selectedDate).toLocaleDateString()} • {selectedTime} - {calculateEndTime()} - -
-
- Duration: - {duration} hour{duration > 1 ? 's' : ''} -
-
- Total Amount: - ₹{totalPrice.toFixed(0)} -
-
-
+ {/* Summary */} +
+

+ Booking Summary +

+
+
+ Date & Time: + + {new Date(selectedDate).toLocaleDateString()} • {selectedTime} -{' '} + {calculateEndTime()} + +
+
+ Duration: + + {duration} hour{duration > 1 ? 's' : ''} + +
+
+ Total Amount: + + {' '} + ₹{totalPrice.toFixed(0)} + +
+
+
- {/* Action Button */} - -
- ) : ( -
- {/* Confirmation Details */} -
-
- -

Booking Details

-
+ {/* Action Button */} + +
+ ) : ( +
+ {/* Confirmation Details */} +
+
+ +

+ Booking Details +

+
-
-
-

Parking Zone

-

{parkingZone?.label}

-
-
-

Slot Number

-

{slot?.title}

-
-
-

Date

-

{new Date(selectedDate).toLocaleDateString()}

-
-
-

Time

-

{selectedTime} - {calculateEndTime()}

-
-
-

Vehicle

-

{vehicleNumber}

-
-
-

Type

-

{vehicleType}

-
-
+
+
+

+ Parking Zone +

+

{parkingZone?.label}

+
+
+

+ Slot Number +

+

{slot?.title}

+
+
+

+ Date +

+

+ {new Date(selectedDate).toLocaleDateString()} +

+
+
+

+ Time +

+

+ {selectedTime} - {calculateEndTime()} +

+
+
+

+ Vehicle +

+

{vehicleNumber}

+
+
+

+ Type +

+

+ {vehicleType} +

+
+
-
-
- Total Amount - ₹{totalPrice.toFixed(0)} -
-
-
+
+
+ Total Amount + + {' '} + ₹{totalPrice.toFixed(0)} + +
+
+
- {/* Important Notice */} -
- -
-

Important Information

-
    -
  • Please arrive within 15 minutes of your booking time
  • -
  • Cancellation allowed up to 1 hour before booking
  • -
  • Keep your booking ID for entry verification
  • -
-
-
+ {/* Important Notice */} +
+ +
+

+ Important Information +

+
    +
  • Please arrive within 15 minutes of your booking time
  • +
  • Cancellation allowed up to 1 hour before booking
  • +
  • Keep your booking ID for entry verification
  • +
+
+
- {/* Action Buttons */} -
- - -
-
- )} - - - - ); + {/* Action Buttons */} +
+ + +
+
+ )} + + + + ); }; export default BookingModal; diff --git a/src/components/parking/QRCodeGenerator.jsx b/src/components/parking/QRCodeGenerator.jsx index 71c48b4..47c5240 100644 --- a/src/components/parking/QRCodeGenerator.jsx +++ b/src/components/parking/QRCodeGenerator.jsx @@ -3,74 +3,72 @@ import { QRCodeSVG } from 'qrcode.react'; import { Download, QrCode as QrIcon, X } from 'lucide-react'; const QRCodeGenerator = ({ booking, onClose }) => { - const qrData = JSON.stringify({ - bookingId: booking.bookingId, - slot: booking.slot?.title, - zone: booking.parkingZone?.label, - date: booking.date, - time: `${booking.startTime} - ${booking.endTime}`, - vehicle: booking.vehicleNumber, - }); + const qrData = JSON.stringify({ + bookingId: booking.bookingId, + slot: booking.slot?.title, + zone: booking.parkingZone?.label, + date: booking.date, + time: `${booking.startTime} - ${booking.endTime}`, + vehicle: booking.vehicleNumber, + }); - const downloadQR = () => { - const canvas = document.getElementById(`qr-${booking.bookingId}`); - const pngUrl = canvas - .toDataURL("image/png") - .replace("image/png", "image/octet-stream"); - const downloadLink = document.createElement("a"); - downloadLink.href = pngUrl; - downloadLink.download = `parking-qr-${booking.bookingId}.png`; - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); - }; + const downloadQR = () => { + const canvas = document.getElementById(`qr-${booking.bookingId}`); + const pngUrl = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); + const downloadLink = document.createElement('a'); + downloadLink.href = pngUrl; + downloadLink.download = `parking-qr-${booking.bookingId}.png`; + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); + }; - return ( -
- -
- -

Entry QR Code

-
+ return ( +
+ +
+ +

Entry QR Code

+
-
- -
+
+ +
-

- Scan this QR code at the parking entrance -

+

+ Scan this QR code at the parking entrance +

-
- +
+ - -
-
- ); + +
+
+ ); }; export default QRCodeGenerator; diff --git a/src/components/parking/RouteOptimizer.jsx b/src/components/parking/RouteOptimizer.jsx index 53e07e4..c930aa7 100644 --- a/src/components/parking/RouteOptimizer.jsx +++ b/src/components/parking/RouteOptimizer.jsx @@ -5,192 +5,217 @@ import { clsx } from 'clsx'; // Calculate distance between two coordinates using Haversine formula const calculateDistance = (lat1, lon1, lat2, lon2) => { - const R = 6371; // Earth's radius in km - const dLat = (lat2 - lat1) * Math.PI / 180; - const dLon = (lon2 - lon1) * Math.PI / 180; - const a = - Math.sin(dLat / 2) * Math.sin(dLat / 2) + - Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * - Math.sin(dLon / 2) * Math.sin(dLon / 2); - const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); - return R * c; // Distance in km + const R = 6371; // Earth's radius in km + const dLat = ((lat2 - lat1) * Math.PI) / 180; + const dLon = ((lon2 - lon1) * Math.PI) / 180; + const a = + Math.sin(dLat / 2) * Math.sin(dLat / 2) + + Math.cos((lat1 * Math.PI) / 180) * + Math.cos((lat2 * Math.PI) / 180) * + Math.sin(dLon / 2) * + Math.sin(dLon / 2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + return R * c; // Distance in km }; // Generate turn-by-turn directions const generateDirections = (userPos, parkingPos, parkingName) => { - const distance = calculateDistance(userPos[0], userPos[1], parkingPos[0], parkingPos[1]); - const bearing = Math.atan2( - parkingPos[1] - userPos[1], - parkingPos[0] - userPos[0] - ) * 180 / Math.PI; - - // Determine cardinal direction - let direction = 'north'; - if (bearing >= -45 && bearing < 45) direction = 'east'; - else if (bearing >= 45 && bearing < 135) direction = 'north'; - else if (bearing >= 135 || bearing < -135) direction = 'west'; - else direction = 'south'; - - // Generate realistic directions - const steps = [ - { instruction: 'Head ' + direction + ' on your current road', distance: 0.1, icon: '🚗' }, - { instruction: 'Continue straight for ' + (distance * 0.4).toFixed(1) + ' km', distance: distance * 0.4, icon: '⬆️' }, - { instruction: 'Turn right onto Main Street', distance: distance * 0.3, icon: '➡️' }, - { instruction: 'Turn left at the traffic signal', distance: distance * 0.2, icon: '⬅️' }, - { instruction: `Arrive at ${parkingName}`, distance: distance * 0.1, icon: '🎯' } - ]; - - return steps; + const distance = calculateDistance(userPos[0], userPos[1], parkingPos[0], parkingPos[1]); + const bearing = + (Math.atan2(parkingPos[1] - userPos[1], parkingPos[0] - userPos[0]) * 180) / Math.PI; + + // Determine cardinal direction + let direction = 'north'; + if (bearing >= -45 && bearing < 45) direction = 'east'; + else if (bearing >= 45 && bearing < 135) direction = 'north'; + else if (bearing >= 135 || bearing < -135) direction = 'west'; + else direction = 'south'; + + // Generate realistic directions + const steps = [ + { instruction: 'Head ' + direction + ' on your current road', distance: 0.1, icon: '🚗' }, + { + instruction: 'Continue straight for ' + (distance * 0.4).toFixed(1) + ' km', + distance: distance * 0.4, + icon: '⬆️', + }, + { instruction: 'Turn right onto Main Street', distance: distance * 0.3, icon: '➡️' }, + { instruction: 'Turn left at the traffic signal', distance: distance * 0.2, icon: '⬅️' }, + { instruction: `Arrive at ${parkingName}`, distance: distance * 0.1, icon: '🎯' }, + ]; + + return steps; }; const RouteOptimizer = ({ userPosition, parkingSpot, onClose }) => { - const [route, setRoute] = useState(null); - const [isCalculating, setIsCalculating] = useState(true); - - useEffect(() => { - if (userPosition && parkingSpot) { - setIsCalculating(true); - - // Simulate route calculation - setTimeout(() => { - const distance = calculateDistance( - userPosition[0], userPosition[1], - parkingSpot.pos[0], parkingSpot.pos[1] - ); - - const avgSpeed = 30; // km/h in city traffic - const estimatedTime = (distance / avgSpeed) * 60; // minutes - - const directions = generateDirections(userPosition, parkingSpot.pos, parkingSpot.label); - - setRoute({ - distance: distance, - duration: estimatedTime, - directions: directions, - trafficLevel: Math.random() > 0.5 ? 'moderate' : 'light' - }); - - setIsCalculating(false); - }, 1500); - } - }, [userPosition, parkingSpot]); - - if (!parkingSpot) return null; - - return ( - - - {/* Header */} -
-
-
- -
-
-

Route to Parking

-

{parkingSpot.label}

-
-
- + const [route, setRoute] = useState(null); + const [isCalculating, setIsCalculating] = useState(true); + + useEffect(() => { + if (userPosition && parkingSpot) { + setIsCalculating(true); + + // Simulate route calculation + setTimeout(() => { + const distance = calculateDistance( + userPosition[0], + userPosition[1], + parkingSpot.pos[0], + parkingSpot.pos[1] + ); + + const avgSpeed = 30; // km/h in city traffic + const estimatedTime = (distance / avgSpeed) * 60; // minutes + + const directions = generateDirections(userPosition, parkingSpot.pos, parkingSpot.label); + + setRoute({ + distance: distance, + duration: estimatedTime, + directions: directions, + trafficLevel: Math.random() > 0.5 ? 'moderate' : 'light', + }); + + setIsCalculating(false); + }, 1500); + } + }, [userPosition, parkingSpot]); + + if (!parkingSpot) return null; + + return ( + + + {/* Header */} +
+
+
+ +
+
+

Route to Parking

+

{parkingSpot.label}

+
+
+ +
+ + {isCalculating ? ( +
+
+

+ Calculating optimal route... +

+
+ ) : route ? ( +
+ {/* Route Summary */} +
+
+ +
+ {route.distance.toFixed(1)}
- - {isCalculating ? ( -
-
-

Calculating optimal route...

+
+ km +
+
+
+ +
+ {Math.ceil(route.duration)} +
+
+ mins +
+
+
+ +
+ {route.trafficLevel} +
+
+ Traffic +
+
+
+ + {/* Alternative Route Info */} +
+
+ + Fastest Route +
+

+ Via Main Street • Avoiding construction on 5th Avenue +

+
+ + {/* Turn-by-Turn Directions */} +
+

+ + Turn-by-Turn Directions +

+
+ {route.directions.map((step, index) => ( + +
+ {step.icon}
- ) : route ? ( -
- {/* Route Summary */} -
-
- -
{route.distance.toFixed(1)}
-
km
-
-
- -
{Math.ceil(route.duration)}
-
mins
-
-
- -
- {route.trafficLevel} -
-
Traffic
-
-
- - {/* Alternative Route Info */} -
-
- - Fastest Route -
-

- Via Main Street • Avoiding construction on 5th Avenue -

-
- - {/* Turn-by-Turn Directions */} -
-

- - Turn-by-Turn Directions -

-
- {route.directions.map((step, index) => ( - -
- {step.icon} -
-
-

{step.instruction}

-

- {step.distance.toFixed(1)} km • {Math.ceil(step.distance / 30 * 60)} min -

-
- -
- ))} -
-
- - {/* Action Buttons */} -
- - -
+
+

+ {step.instruction} +

+

+ {step.distance.toFixed(1)} km • {Math.ceil((step.distance / 30) * 60)} min +

- ) : null} - - - ); + + + ))} +
+
+ + {/* Action Buttons */} +
+ + +
+
+ ) : null} + + + ); }; export default RouteOptimizer; diff --git a/src/components/parking/SlotGrid.jsx b/src/components/parking/SlotGrid.jsx index 12cc583..f099f2e 100644 --- a/src/components/parking/SlotGrid.jsx +++ b/src/components/parking/SlotGrid.jsx @@ -4,73 +4,84 @@ import { motion } from 'framer-motion'; import { Zap } from 'lucide-react'; const SlotGrid = ({ slots = [], onSlotClick }) => { - const safeSlots = Array.isArray(slots) ? slots : []; - if (safeSlots.length === 0) { - return ( -
-

Loading slots for selected zone...

-
- ); - } + const safeSlots = Array.isArray(slots) ? slots : []; + if (safeSlots.length === 0) { return ( -
- {safeSlots.map((slot) => ( - onSlotClick(slot)} - className={clsx( - "aspect-[3/4] rounded-xl flex flex-col items-center justify-center border-2 transition-all duration-300 relative overflow-hidden group", - slot.status === 'free' - ? "bg-brand-green/10 border-brand-green/30 hover:bg-brand-green/20" - : slot.status === 'occupied' - ? "bg-brand-red/10 border-brand-red/30 hover:bg-brand-red/20 opacity-90" - : "bg-brand-yellow/10 border-brand-yellow/30 hover:bg-brand-yellow/20" // Reserved - )} - > - {/* Status Indicator Glow */} -
+
+

Loading slots for selected zone...

+
+ ); + } + return ( +
+ {safeSlots.map((slot) => ( + onSlotClick(slot)} + className={clsx( + 'aspect-[3/4] rounded-xl flex flex-col items-center justify-center border-2 transition-all duration-300 relative overflow-hidden group', + slot.status === 'free' + ? 'bg-brand-green/10 border-brand-green/30 hover:bg-brand-green/20' + : slot.status === 'occupied' + ? 'bg-brand-red/10 border-brand-red/30 hover:bg-brand-red/20 opacity-90' + : 'bg-brand-yellow/10 border-brand-yellow/30 hover:bg-brand-yellow/20' // Reserved + )} + > + {/* Status Indicator Glow */} +
- {/* EV Charging Badge */} - {slot.isEV && ( -
- -
- )} + {/* EV Charging Badge */} + {slot.isEV && ( +
+ +
+ )} - - {slot.title} - + + {slot.title} + - - {slot.status} - {slot.isEV && (EV)} - + + {slot.status} + {slot.isEV && (EV)} + - {slot.status === 'occupied' && ( -
- - {slot.isEV ? '⚡ Charging' : 'Occupied'} -
- {slot.vehicleId || '---'} -
-
- )} -
- ))} -
- ); + {slot.status === 'occupied' && ( +
+ + {slot.isEV ? '⚡ Charging' : 'Occupied'} +
+ {slot.vehicleId || '---'} +
+
+ )} +
+ ))} +
+ ); }; export default SlotGrid; diff --git a/src/components/payment/PaymentModal.jsx b/src/components/payment/PaymentModal.jsx index d10f64e..1c17c9b 100644 --- a/src/components/payment/PaymentModal.jsx +++ b/src/components/payment/PaymentModal.jsx @@ -1,560 +1,605 @@ import React, { useState } from 'react'; -import { X, CheckCircle2, Loader2, Lock, ShieldCheck, CreditCard, QrCode, Smartphone, Sparkles, ChevronRight, Check } from 'lucide-react'; +import { + X, + CheckCircle2, + Loader2, + Lock, + ShieldCheck, + CreditCard, + QrCode, + Smartphone, + Sparkles, + ChevronRight, + Check, +} from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; import { useStripe, useElements, CardElement } from '@stripe/react-stripe-js'; import { bookingAPI } from '../../services/api'; const PaymentModal = ({ booking, onClose, onSuccess }) => { - const stripe = useStripe(); - const elements = useElements(); - - const [paymentMethod, setPaymentMethod] = useState('card'); // 'card', 'upi', 'wallet' - const [cardHolder, setCardHolder] = useState(''); - const [cardNumber, setCardNumber] = useState(''); - const [cardExpiry, setCardExpiry] = useState(''); - const [cardCvc, setCardCvc] = useState(''); - const [isFlipped, setIsFlipped] = useState(false); - - const [processing, setProcessing] = useState(false); - const [processingStep, setProcessingStep] = useState('Initializing...'); - const [error, setError] = useState(null); - const [success, setSuccess] = useState(false); - - // Detect Card Brand based on number - const getCardBrand = (num) => { - const clean = (num || '').replace(/\s+/g, ''); - if (clean.startsWith('4')) return 'VISA'; - if (clean.startsWith('5') || clean.startsWith('2')) return 'MASTERCARD'; - if (clean.startsWith('3')) return 'AMEX'; - if (clean.startsWith('6')) return 'RUPAY'; - return 'CARD'; - }; - - const validateExpiryDate = (expiryStr) => { - if (!expiryStr || !expiryStr.includes('/')) return false; - const parts = expiryStr.split('/'); - if (parts.length !== 2) return false; - const month = parseInt(parts[0], 10); - const year = parseInt(parts[1], 10); - - if (isNaN(month) || isNaN(year)) return false; - if (month < 1 || month > 12) return false; - - const now = new Date(); - const currentYear = parseInt(now.getFullYear().toString().slice(-2), 10); - const currentMonth = now.getMonth() + 1; - - if (year < currentYear) return false; - if (year === currentYear && month < currentMonth) return false; - - return true; - }; - - const handleNumberChange = (e) => { - const val = e.target.value.replace(/\D/g, '').slice(0, 12); - const formatted = val.replace(/(.{4})/g, '$1 ').trim(); - setCardNumber(formatted); - }; - - const handleExpiryChange = (e) => { - const raw = e.target.value.replace(/\D/g, '').slice(0, 4); - if (raw.length >= 3) { - setCardExpiry(`${raw.slice(0, 2)}/${raw.slice(2)}`); - } else if (raw.length === 2 && e.nativeEvent.inputType !== 'deleteContentBackward') { - setCardExpiry(`${raw}/`); - } else { - setCardExpiry(raw); - } - }; - - const handleSubmit = async (e) => { - if (e) e.preventDefault(); - - setError(null); - - // Mandatory Card Field Validation - if (paymentMethod === 'card') { - const cleanNum = (cardNumber || '').replace(/\D/g, ''); - const cleanCvc = (cardCvc || '').trim(); - const cleanExpiry = (cardExpiry || '').trim(); - - if (!cardHolder.trim()) { - setError("Cardholder Name is required (*)"); - return; - } - if (!cleanNum || cleanNum.length !== 12) { - setError("Invalid card details: Card Number must contain exactly 12 digits (*)"); - return; - } - if (!validateExpiryDate(cleanExpiry)) { - setError("Invalid card details: Expiry Date month must be between 01-12 and date cannot be in the past (*)"); - return; - } - if (!cleanCvc || cleanCvc.length < 3) { - setError("Invalid card details: Valid 3-digit CVV number is required (*)"); - return; - } + const stripe = useStripe(); + const elements = useElements(); + + const [paymentMethod, setPaymentMethod] = useState('card'); // 'card', 'upi', 'wallet' + const [cardHolder, setCardHolder] = useState(''); + const [cardNumber, setCardNumber] = useState(''); + const [cardExpiry, setCardExpiry] = useState(''); + const [cardCvc, setCardCvc] = useState(''); + const [isFlipped, setIsFlipped] = useState(false); + + const [processing, setProcessing] = useState(false); + const [processingStep, setProcessingStep] = useState('Initializing...'); + const [error, setError] = useState(null); + const [success, setSuccess] = useState(false); + + // Detect Card Brand based on number + const getCardBrand = (num) => { + const clean = (num || '').replace(/\s+/g, ''); + if (clean.startsWith('4')) return 'VISA'; + if (clean.startsWith('5') || clean.startsWith('2')) return 'MASTERCARD'; + if (clean.startsWith('3')) return 'AMEX'; + if (clean.startsWith('6')) return 'RUPAY'; + return 'CARD'; + }; + + const validateExpiryDate = (expiryStr) => { + if (!expiryStr || !expiryStr.includes('/')) return false; + const parts = expiryStr.split('/'); + if (parts.length !== 2) return false; + const month = parseInt(parts[0], 10); + const year = parseInt(parts[1], 10); + + if (isNaN(month) || isNaN(year)) return false; + if (month < 1 || month > 12) return false; + + const now = new Date(); + const currentYear = parseInt(now.getFullYear().toString().slice(-2), 10); + const currentMonth = now.getMonth() + 1; + + if (year < currentYear) return false; + if (year === currentYear && month < currentMonth) return false; + + return true; + }; + + const handleNumberChange = (e) => { + const val = e.target.value.replace(/\D/g, '').slice(0, 12); + const formatted = val.replace(/(.{4})/g, '$1 ').trim(); + setCardNumber(formatted); + }; + + const handleExpiryChange = (e) => { + const raw = e.target.value.replace(/\D/g, '').slice(0, 4); + if (raw.length >= 3) { + setCardExpiry(`${raw.slice(0, 2)}/${raw.slice(2)}`); + } else if (raw.length === 2 && e.nativeEvent.inputType !== 'deleteContentBackward') { + setCardExpiry(`${raw}/`); + } else { + setCardExpiry(raw); + } + }; + + const handleSubmit = async (e) => { + if (e) e.preventDefault(); + + setError(null); + + // Mandatory Card Field Validation + if (paymentMethod === 'card') { + const cleanNum = (cardNumber || '').replace(/\D/g, ''); + const cleanCvc = (cardCvc || '').trim(); + const cleanExpiry = (cardExpiry || '').trim(); + + if (!cardHolder.trim()) { + setError('Cardholder Name is required (*)'); + return; + } + if (!cleanNum || cleanNum.length !== 12) { + setError('Invalid card details: Card Number must contain exactly 12 digits (*)'); + return; + } + if (!validateExpiryDate(cleanExpiry)) { + setError( + 'Invalid card details: Expiry Date month must be between 01-12 and date cannot be in the past (*)' + ); + return; + } + if (!cleanCvc || cleanCvc.length < 3) { + setError('Invalid card details: Valid 3-digit CVV number is required (*)'); + return; + } + } + + setProcessing(true); + setProcessingStep('Encrypting security payload...'); + + setTimeout(() => setProcessingStep('Verifying token with bank...'), 800); + setTimeout(() => setProcessingStep('Authorizing transaction...'), 1600); + + try { + const targetBookingId = booking?._id || booking?.id || booking?.bookingId; + + let clientSecret = null; + if ( + targetBookingId && + !String(targetBookingId).startsWith('bk_local_') && + stripe && + elements && + paymentMethod === 'card' + ) { + try { + const response = await Promise.race([ + bookingAPI.createPaymentIntent(targetBookingId), + new Promise((_, reject) => + setTimeout(() => reject(new Error('Backend payment intent timeout')), 2500) + ), + ]); + if (response && response.clientSecret) { + clientSecret = response.clientSecret; + } + } catch (backendErr) { + console.warn('Backend Stripe Intent notice:', backendErr.message); } + } + + // Real Stripe payment processing if clientSecret exists + if (clientSecret && clientSecret !== 'MOCK_DEMO_SECRET' && stripe && elements) { + const cardEl = elements.getElement(CardElement); + if (cardEl) { + const result = await stripe.confirmCardPayment(clientSecret, { + payment_method: { + card: cardEl, + billing_details: { name: cardHolder || 'Guest User' }, + }, + }); - setProcessing(true); - setProcessingStep('Encrypting security payload...'); - - setTimeout(() => setProcessingStep('Verifying token with bank...'), 800); - setTimeout(() => setProcessingStep('Authorizing transaction...'), 1600); + if (result.error) { + setProcessing(false); + setError(result.error.message || 'Payment authorization failed'); + return; + } - try { - const targetBookingId = booking?._id || booking?.id || booking?.bookingId; - - let clientSecret = null; - if (targetBookingId && !String(targetBookingId).startsWith('bk_local_') && stripe && elements && paymentMethod === 'card') { - try { - const response = await Promise.race([ - bookingAPI.createPaymentIntent(targetBookingId), - new Promise((_, reject) => setTimeout(() => reject(new Error('Backend payment intent timeout')), 2500)) - ]); - if (response && response.clientSecret) { - clientSecret = response.clientSecret; - } - } catch (backendErr) { - console.warn("Backend Stripe Intent notice:", backendErr.message); - } - } - - // Real Stripe payment processing if clientSecret exists - if (clientSecret && clientSecret !== 'MOCK_DEMO_SECRET' && stripe && elements) { - const cardEl = elements.getElement(CardElement); - if (cardEl) { - const result = await stripe.confirmCardPayment(clientSecret, { - payment_method: { - card: cardEl, - billing_details: { name: cardHolder || 'Guest User' }, - }, - }); - - if (result.error) { - setProcessing(false); - setError(result.error.message || 'Payment authorization failed'); - return; - } - - if (result.paymentIntent?.status === 'succeeded') { - setSuccess(true); - setProcessing(false); - setTimeout(() => { - onSuccess({ - ...booking, - paymentId: result.paymentIntent.id, - paymentMethod: 'card', - paymentStatus: 'completed', - paidAt: new Date().toISOString() - }); - }, 1400); - return; - } - } - } - - // Demo / Test payment authorization for local bookings - setTimeout(() => { - setSuccess(true); - setProcessing(false); - setTimeout(() => { - onSuccess({ - ...booking, - paymentId: 'tx_demo_' + Date.now(), - paymentMethod: paymentMethod, - paymentStatus: 'completed', - paidAt: new Date().toISOString() - }); - }, 1400); - }, 1200); - - } catch (err) { + if (result.paymentIntent?.status === 'succeeded') { + setSuccess(true); setProcessing(false); - setError(err.message || 'Payment processing failed. Please check your card details and try again.'); + setTimeout(() => { + onSuccess({ + ...booking, + paymentId: result.paymentIntent.id, + paymentMethod: 'card', + paymentStatus: 'completed', + paidAt: new Date().toISOString(), + }); + }, 1400); + return; + } } - }; - - const cardElementOptions = { - style: { - base: { - color: '#ffffff', - fontFamily: '"Outfit", sans-serif', - fontSmoothing: 'antialiased', - fontSize: '15px', - '::placeholder': { - color: '#64748b', - }, - }, - invalid: { - color: '#ef4444', - iconColor: '#ef4444', - }, - }, - }; - - return ( - + } + + // Demo / Test payment authorization for local bookings + setTimeout(() => { + setSuccess(true); + setProcessing(false); + setTimeout(() => { + onSuccess({ + ...booking, + paymentId: 'tx_demo_' + Date.now(), + paymentMethod: paymentMethod, + paymentStatus: 'completed', + paidAt: new Date().toISOString(), + }); + }, 1400); + }, 1200); + } catch (err) { + setProcessing(false); + setError( + err.message || 'Payment processing failed. Please check your card details and try again.' + ); + } + }; + + return ( + + + e.stopPropagation()} + className="glass-panel rounded-3xl p-6 sm:p-8 max-w-lg w-full border border-slate-200 dark:border-white/10 relative overflow-hidden shadow-2xl my-8" + > + {/* Glowing Top Gradient Bar */} +
+
+ + {success ? ( + /* SUCCESS CELEBRATION ANIMATION */ +
+ e.stopPropagation()} - className="glass-panel rounded-3xl p-6 sm:p-8 max-w-lg w-full border border-slate-200 dark:border-white/10 relative overflow-hidden shadow-2xl my-8" + initial={{ scale: 0 }} + animate={{ scale: [0, 1.2, 1] }} + transition={{ duration: 0.6, times: [0, 0.7, 1] }} + className="w-24 h-24 bg-brand-green/20 rounded-full flex items-center justify-center border border-brand-green/40 shadow-[0_0_40px_rgba(0,255,157,0.3)]" > - {/* Glowing Top Gradient Bar */} -
-
- - {success ? ( - /* SUCCESS CELEBRATION ANIMATION */ - -
- - - - -
- + +
+
+ +
+

+ Payment Verified! +

+

+ Slot{' '} + + {booking?.slot?.title || 'Reservation'} + {' '} + is confirmed +

+
+ +
+
+ Amount Paid + + ₹{booking?.totalPrice?.toFixed(0) || '100'} INR + +
+
+ Payment Method + + {paymentMethod} + +
+
+ Status + + Instant Verified + +
+
+ +
+ Generating Entry QR Pass... +
+
+ ) : ( +
+ {/* Modal Header */} +
+
+
+ +
+
+

+ Checkout{' '} + + 256-Bit SSL + +

+

+ TraffiTech Payment Terminal +

+
+
+ +
+ + {/* Payable Amount Display */} +
+
+ + Total Payable + +
+ + ₹{booking?.totalPrice?.toFixed(0) || '100'} + + INR +
+
+
+

+ {booking?.parkingZone?.label || 'City Mall Parking'} +

+

Slot {booking?.slot?.title || 'P-1'} • 2 Hours

+
+
+ + {/* Payment Method Tabs */} +
+ +
+ {[ + { id: 'card', label: 'Credit Card', icon: CreditCard }, + { id: 'upi', label: 'UPI / QR', icon: QrCode }, + { id: 'wallet', label: 'Apple / GPay', icon: Smartphone }, + ].map((m) => ( + + ))} +
+
+ + {/* DYNAMIC ANIMATED CREDIT CARD PREVIEW */} + {paymentMethod === 'card' && ( +
+ + {/* Card Shiny Overlay */} +
+
+ + {!isFlipped ? ( + /* FRONT OF CARD */ +
+
+ {/* Chip Graphic */} +
+
+
+ + {getCardBrand(cardNumber)} + +
+ +
+ + Card Number + +

+ {cardNumber || '•••• •••• ••••'} +

+
-

Payment Verified!

-

- Slot {booking?.slot?.title || 'Reservation'} is confirmed -

-
- -
-
- Amount Paid - ₹{booking?.totalPrice?.toFixed(0) || '100'} INR -
-
- Payment Method - {paymentMethod} -
-
- Status - - Instant Verified - -
+ + Cardholder + +

+ {cardHolder || 'YOUR NAME'} +

- -
- Generating Entry QR Pass... +
+ + Expires + +

+ {cardExpiry || 'MM/YY'} +

- +
+
+
) : ( - - {/* Modal Header */} -
-
-
- -
-
-

- Checkout 256-Bit SSL -

-

TraffiTech Payment Terminal

-
-
- -
- - {/* Payable Amount Display */} -
-
- Total Payable -
- ₹{booking?.totalPrice?.toFixed(0) || '100'} - INR -
-
-
-

{booking?.parkingZone?.label || 'City Mall Parking'}

-

Slot {booking?.slot?.title || 'P-1'} • 2 Hours

-
-
- - {/* Payment Method Tabs */} -
- -
- {[ - { id: 'card', label: 'Credit Card', icon: CreditCard }, - { id: 'upi', label: 'UPI / QR', icon: QrCode }, - { id: 'wallet', label: 'Apple / GPay', icon: Smartphone } - ].map((m) => ( - - ))} -
-
- - {/* DYNAMIC ANIMATED CREDIT CARD PREVIEW */} - {paymentMethod === 'card' && ( -
- - {/* Card Shiny Overlay */} -
-
- - {!isFlipped ? ( - /* FRONT OF CARD */ -
-
- {/* Chip Graphic */} -
-
-
- - {getCardBrand(cardNumber)} - -
- -
- Card Number -

- {cardNumber || '•••• •••• ••••'} -

-
-
- Cardholder -

- {cardHolder || 'YOUR NAME'} -

-
-
- Expires -

- {cardExpiry || 'MM/YY'} -

-
-
-
-
- ) : ( - /* BACK OF CARD */ -
-
-
-
- - {cardCvc || '•••'} - -
- CVV / Security Code -
-
- Authorized Signature • End-To-End Encrypted -
-
- )} -
-
- )} - - {/* CARD / METHOD INPUT FIELDS */} - {paymentMethod === 'card' && ( -
-
- - setCardHolder(e.target.value.toUpperCase())} - onFocus={() => setIsFlipped(false)} - placeholder="e.g. ALEX JOHNSON" - className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-semibold text-slate-800 dark:text-white focus:outline-none focus:border-brand-blue transition-all" - /> -
- -
- -
- setIsFlipped(false)} - placeholder="•••• •••• ••••" - maxLength={14} - className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-mono text-slate-800 dark:text-white focus:outline-none focus:border-brand-blue transition-all" - /> - - {getCardBrand(cardNumber)} - -
-
- -
-
- - setIsFlipped(false)} - placeholder="MM/YY" - className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-mono text-slate-800 dark:text-white focus:outline-none focus:border-brand-blue transition-all" - /> -
-
- - setCardCvc(e.target.value)} - onFocus={() => setIsFlipped(true)} - onBlur={() => setIsFlipped(false)} - placeholder="•••" - className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-mono text-slate-800 dark:text-white text-center focus:outline-none focus:border-brand-blue transition-all" - /> -
-
-
- )} - - {paymentMethod === 'upi' && ( -
-
- -
-

Scan QR using GPay, PhonePe, Paytm or Enter VPA

- -
- )} - - {paymentMethod === 'wallet' && ( -
-
- -
-

Express 1-Click Checkout

-

Instant biometric payment via Apple Pay or Google Wallet

-
- )} - - {error && ( - -
- {error} -
- )} - - {/* Processing Progress Status Banner */} - {processing && ( - - - - {processingStep} - - PROCESSING - - )} - - {/* Security Badge */} -
- - End-to-end encrypted • Guaranteed Instant Pass -
- - {/* SUBMIT CHECKOUT BUTTON */} - - + /* BACK OF CARD */ +
+
+
+
+ + {cardCvc || '•••'} + +
+ + CVV / Security Code + +
+
+ Authorized Signature • End-To-End Encrypted +
+
)} + +
+ )} + + {/* CARD / METHOD INPUT FIELDS */} + {paymentMethod === 'card' && ( +
+
+ + setCardHolder(e.target.value.toUpperCase())} + onFocus={() => setIsFlipped(false)} + placeholder="e.g. ALEX JOHNSON" + className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-semibold text-slate-800 dark:text-white focus:outline-none focus:border-brand-blue transition-all" + /> +
+ +
+ +
+ setIsFlipped(false)} + placeholder="•••• •••• ••••" + maxLength={14} + className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-mono text-slate-800 dark:text-white focus:outline-none focus:border-brand-blue transition-all" + /> + + {getCardBrand(cardNumber)} + +
+
+ +
+
+ + setIsFlipped(false)} + placeholder="MM/YY" + className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-mono text-slate-800 dark:text-white focus:outline-none focus:border-brand-blue transition-all" + /> +
+
+ + setCardCvc(e.target.value)} + onFocus={() => setIsFlipped(true)} + onBlur={() => setIsFlipped(false)} + placeholder="•••" + className="w-full px-4 py-2.5 bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl text-sm font-mono text-slate-800 dark:text-white text-center focus:outline-none focus:border-brand-blue transition-all" + /> +
+
+
+ )} + + {paymentMethod === 'upi' && ( +
+
+ +
+

+ Scan QR using GPay, PhonePe, Paytm or Enter VPA +

+ +
+ )} + + {paymentMethod === 'wallet' && ( +
+
+ +
+

+ Express 1-Click Checkout +

+

+ Instant biometric payment via Apple Pay or Google Wallet +

+
+ )} + + {error && ( + +
+ {error}
-
- - ); + )} + + {/* Processing Progress Status Banner */} + {processing && ( + + + + {processingStep} + + PROCESSING + + )} + + {/* Security Badge */} +
+ + End-to-end encrypted • Guaranteed Instant Pass +
+ + {/* SUBMIT CHECKOUT BUTTON */} + + + )} + + + + ); }; export default PaymentModal; diff --git a/src/components/traffic/IntersectionMap.jsx b/src/components/traffic/IntersectionMap.jsx index d0d73bc..307219d 100644 --- a/src/components/traffic/IntersectionMap.jsx +++ b/src/components/traffic/IntersectionMap.jsx @@ -3,135 +3,194 @@ import { clsx } from 'clsx'; import { motion } from 'framer-motion'; const TrafficLight = ({ state }) => ( -
-
-
-
-
+
+
+
+
+
); const IntersectionMap = ({ signals, density, emergencySource }) => { - return ( -
- {/* Background Texture (Asphalt) */} -
-
+ return ( +
+ {/* Background Texture (Asphalt) */} +
- {/* Emergency Intersection Strobe Overlay */} - {emergencySource && ( -
-
-
- )} + {/* Emergency Intersection Strobe Overlay */} + {emergencySource && ( +
+
+
+ )} - {/* Roads */} -
- {/* Vertical Road Markings */} -
-
-
- {/* Horizontal Road Markings */} -
-
+ {/* Roads */} +
+ {/* Vertical Road Markings */} +
+
+
+ {/* Horizontal Road Markings */} +
+
- {/* Crosswalks */} -
-
-
-
+ {/* Crosswalks */} +
+
+
+
- {/* Traffic Lights Positioning */} -
-
-
-
+ {/* Traffic Lights Positioning */} +
+ +
+
+ +
+
+ +
+
+ +
- {/* Emergency Vehicle - Dynamic preemption corridors */} - {emergencySource === 'N' && ( - -
-
-
-
-
EMT
-
- )} + {/* Emergency Vehicle - Dynamic preemption corridors */} + {emergencySource === 'N' && ( + +
+
+
+
+
+ EMT +
+
+ )} - {emergencySource === 'S' && ( - -
-
-
-
-
EMT
-
- )} + {emergencySource === 'S' && ( + +
+
+
+
+
+ EMT +
+
+ )} - {emergencySource === 'W' && ( - -
-
-
-
-
EMT
-
- )} + {emergencySource === 'W' && ( + +
+
+
+
+
EMT
+
+ )} - {emergencySource === 'E' && ( - -
-
-
-
-
EMT
-
- )} + {emergencySource === 'E' && ( + +
+
+
+
+
EMT
+
+ )} - {/* Simulated Cars (Animation based on Density) */} - - - - + {/* Simulated Cars (Animation based on Density) */} + + + + - {/* Legend */} -
- Live Simulation • 4-Way -
-
- ); + {/* Legend */} +
+ Live Simulation • 4-Way +
+
+ ); }; export default IntersectionMap; diff --git a/src/components/traffic/LiveCityMap.jsx b/src/components/traffic/LiveCityMap.jsx index cc30d06..6fd19a3 100644 --- a/src/components/traffic/LiveCityMap.jsx +++ b/src/components/traffic/LiveCityMap.jsx @@ -1,4 +1,3 @@ - import React, { useState, useEffect } from 'react'; import { MapContainer, TileLayer, Marker, Popup, Circle, useMap } from 'react-leaflet'; import 'leaflet/dist/leaflet.css'; @@ -13,176 +12,257 @@ import iconShadow from 'leaflet/dist/images/marker-shadow.png'; delete L.Icon.Default.prototype._getIconUrl; L.Icon.Default.mergeOptions({ - iconRetinaUrl: iconRetina, - iconUrl: iconMarker, - shadowUrl: iconShadow, + iconRetinaUrl: iconRetina, + iconUrl: iconMarker, + shadowUrl: iconShadow, }); // Custom Marker Generator const customIcon = (type) => { - let colorClass = 'bg-blue-500'; - let shadowClass = 'shadow-blue-500/50'; - - if (type === 'red') { colorClass = 'bg-red-500'; shadowClass = 'shadow-red-500/50'; } - if (type === 'green') { colorClass = 'bg-green-500'; shadowClass = 'shadow-green-500/50'; } - if (type === 'parking') { colorClass = 'bg-purple-500'; shadowClass = 'shadow-purple-500/50'; } - if (type === 'user') { colorClass = 'bg-brand-blue animate-pulse'; shadowClass = 'shadow-brand-blue/50'; } - - return divIcon({ - className: 'custom-icon', - html: `
`, - iconSize: [16, 16] - }); + let colorClass = 'bg-blue-500'; + let shadowClass = 'shadow-blue-500/50'; + + if (type === 'red') { + colorClass = 'bg-red-500'; + shadowClass = 'shadow-red-500/50'; + } + if (type === 'green') { + colorClass = 'bg-green-500'; + shadowClass = 'shadow-green-500/50'; + } + if (type === 'parking') { + colorClass = 'bg-purple-500'; + shadowClass = 'shadow-purple-500/50'; + } + if (type === 'user') { + colorClass = 'bg-brand-blue animate-pulse'; + shadowClass = 'shadow-brand-blue/50'; + } + + return divIcon({ + className: 'custom-icon', + html: `
`, + iconSize: [16, 16], + }); }; // Component to recenter map when position changes const RecenterMap = ({ position }) => { - const map = useMap(); - useEffect(() => { - map.flyTo(position, 15); - }, [position, map]); - return null; + const map = useMap(); + useEffect(() => { + map.flyTo(position, 15); + }, [position, map]); + return null; }; const LiveCityMap = () => { - const [userPosition, setUserPosition] = useState([12.9716, 77.5946]); // Default: Bangalore - const [parkingSpots, setParkingSpots] = useState([]); - const [status, setStatus] = useState('initializing'); // initializing, locating, ready, error - - useEffect(() => { - setStatus('locating'); - if (navigator.geolocation) { - navigator.geolocation.getCurrentPosition( - (pos) => { - const { latitude, longitude } = pos.coords; - const newPos = [latitude, longitude]; - setUserPosition(newPos); - setStatus('ready'); - - // Generate "Nearby" parking spots based on real location - setParkingSpots([ - { id: 'p1', pos: [latitude + 0.002, longitude + 0.002], label: "Mall Parking", available: 12 }, - { id: 'p2', pos: [latitude - 0.0015, longitude + 0.001], label: "Metro Station", available: 5 }, - { id: 'p3', pos: [latitude + 0.001, longitude - 0.002], label: "Public Park Lot", available: 0 }, // Full - ]); - }, - (err) => { - console.error("Location access denied", err); - setStatus('error'); - } - ); - } else { - setStatus('error'); + const [userPosition, setUserPosition] = useState([12.9716, 77.5946]); // Default: Bangalore + const [parkingSpots, setParkingSpots] = useState([]); + const [status, setStatus] = useState('initializing'); // initializing, locating, ready, error + + useEffect(() => { + setStatus('locating'); + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition( + (pos) => { + const { latitude, longitude } = pos.coords; + const newPos = [latitude, longitude]; + setUserPosition(newPos); + setStatus('ready'); + + // Generate "Nearby" parking spots based on real location + setParkingSpots([ + { + id: 'p1', + pos: [latitude + 0.002, longitude + 0.002], + label: 'Mall Parking', + available: 12, + }, + { + id: 'p2', + pos: [latitude - 0.0015, longitude + 0.001], + label: 'Metro Station', + available: 5, + }, + { + id: 'p3', + pos: [latitude + 0.001, longitude - 0.002], + label: 'Public Park Lot', + available: 0, + }, // Full + ]); + }, + (err) => { + console.error('Location access denied', err); + setStatus('error'); } - }, []); - - const trafficPoints = [ - { id: 1, pos: [userPosition[0] + 0.001, userPosition[1] + 0.001], status: 'red', label: "Junction A" }, - { id: 2, pos: [userPosition[0] - 0.002, userPosition[1] - 0.001], status: 'green', label: "Junction B" }, - ]; - - return ( -
- {/* Map Wrapper */} -
- {/* Map Container */} - - - - - - {/* User Location */} - -
You are Here
-
- - - {/* Traffic Signals */} - {trafficPoints.map(point => ( - - -
{point.label}
-
- Signal: {point.status} -
-
-
- ))} - - {/* Parking Spots */} - {parkingSpots.map(spot => ( - - -
{spot.label}
-
{spot.available > 0 ? `${spot.available} Slots Free` : 'FULL'}
-
-
- ))} -
- - {/* Status Overlays */} -
- {/* GPS Status */} -
- {status === 'locating' && } - {status === 'ready' && } - {status === 'error' && } - - {status === 'locating' ? "Bypassing Firewall..." : status === 'ready' ? "Encrypted GPS Link" : "Signal Jammed"} - -
- - {/* Map Legend (Desktop/Tablet only) */} -
-

Traffic Intelligence

-
-
-
- Current Ops Center -
-
-
- Tactical Parking -
-
-
-
-
-
- Signal Nodes -
-
-
+ ); + } else { + setStatus('error'); + } + }, []); + + const trafficPoints = [ + { + id: 1, + pos: [userPosition[0] + 0.001, userPosition[1] + 0.001], + status: 'red', + label: 'Junction A', + }, + { + id: 2, + pos: [userPosition[0] - 0.002, userPosition[1] - 0.001], + status: 'green', + label: 'Junction B', + }, + ]; + + return ( +
+ {/* Map Wrapper */} +
+ {/* Map Container */} + + + + + + {/* User Location */} + + +
You are Here
+
+
+ + + {/* Traffic Signals */} + {trafficPoints.map((point) => ( + + +
{point.label}
+
+ Signal: {point.status}
-
+ + + ))} + + {/* Parking Spots */} + {parkingSpots.map((spot) => ( + + +
{spot.label}
+
+ {spot.available > 0 ? `${spot.available} Slots Free` : 'FULL'} +
+
+
+ ))} + + + {/* Status Overlays */} +
+ {/* GPS Status */} +
+ {status === 'locating' && ( + + )} + {status === 'ready' && ( + + )} + {status === 'error' && ( + + )} + + {status === 'locating' + ? 'Bypassing Firewall...' + : status === 'ready' + ? 'Encrypted GPS Link' + : 'Signal Jammed'} + +
- {/* Mobile Map Legend (Visible only on Mobile below md breakpoint) */} -
-

Traffic Intelligence

-
-
-
- Current Ops Center -
-
-
- Tactical Parking -
-
-
-
-
-
- Signal Nodes -
+ {/* Map Legend (Desktop/Tablet only) */} +
+

+ Traffic Intelligence +

+
+
+
+ + Current Ops Center + +
+
+
+ + Tactical Parking + +
+
+
+
+
+ + Signal Nodes + +
+
- ); +
+ + {/* Mobile Map Legend (Visible only on Mobile below md breakpoint) */} +
+

+ Traffic Intelligence +

+
+
+
+ + Current Ops Center + +
+
+
+ + Tactical Parking + +
+
+
+
+
+
+ + Signal Nodes + +
+
+
+
+ ); }; export default LiveCityMap; - diff --git a/src/components/traffic/SignalControl.jsx b/src/components/traffic/SignalControl.jsx index 3c09fae..acfb5e4 100644 --- a/src/components/traffic/SignalControl.jsx +++ b/src/components/traffic/SignalControl.jsx @@ -3,42 +3,46 @@ import { clsx } from 'clsx'; import { Clock } from 'lucide-react'; const SignalControl = ({ signalId, currentLight, setLight, duration }) => { - const lights = [ - { color: 'red', label: 'STOP', value: 'red' }, - { color: 'yellow', label: 'WAIT', value: 'yellow' }, - { color: 'green', label: 'GO', value: 'green' }, - ]; + const lights = [ + { color: 'red', label: 'STOP', value: 'red' }, + { color: 'yellow', label: 'WAIT', value: 'yellow' }, + { color: 'green', label: 'GO', value: 'green' }, + ]; - return ( -
-
-

Signal {signalId}

-
- - {duration}s -
-
- -
- {lights.map((l) => ( - - ))} -
+ return ( +
+
+

+ Signal {signalId} +

+
+ + {duration}s
- ); +
+ +
+ {lights.map((l) => ( + + ))} +
+
+ ); }; export default SignalControl; diff --git a/src/context/AppContext.jsx b/src/context/AppContext.jsx index 9c8255b..a48f85c 100644 --- a/src/context/AppContext.jsx +++ b/src/context/AppContext.jsx @@ -3,30 +3,32 @@ import React, { createContext, useContext, useState } from 'react'; const AppContext = createContext(); export const useApp = () => { - const context = useContext(AppContext); - if (!context) { - throw new Error('useApp must be used within AppProvider'); - } - return context; + const context = useContext(AppContext); + if (!context) { + throw new Error('useApp must be used within AppProvider'); + } + return context; }; export const AppProvider = ({ children }) => { - const [emergencyMode, setEmergencyMode] = useState(false); - const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); + const [emergencyMode, setEmergencyMode] = useState(false); + const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); - const toggleEmergency = () => setEmergencyMode(prev => !prev); - const toggleMobileMenu = () => setIsMobileMenuOpen(prev => !prev); - const closeMobileMenu = () => setIsMobileMenuOpen(false); + const toggleEmergency = () => setEmergencyMode((prev) => !prev); + const toggleMobileMenu = () => setIsMobileMenuOpen((prev) => !prev); + const closeMobileMenu = () => setIsMobileMenuOpen(false); - return ( - - {children} - - ); + return ( + + {children} + + ); }; diff --git a/src/hooks/useIoT.js b/src/hooks/useIoT.js index a17bbe0..b7f80a8 100644 --- a/src/hooks/useIoT.js +++ b/src/hooks/useIoT.js @@ -4,29 +4,29 @@ import { io } from 'socket.io-client'; const SOCKET_URL = '/'; export const useIoT = () => { - const [iotData, setIotData] = useState(null); - const [connected, setConnected] = useState(false); + const [iotData, setIotData] = useState(null); + const [connected, setConnected] = useState(false); - useEffect(() => { - const socket = io(SOCKET_URL); + useEffect(() => { + const socket = io(SOCKET_URL); - socket.on('connect', () => { - setConnected(true); - console.log('Connected to IoT Stream'); - }); + socket.on('connect', () => { + setConnected(true); + console.log('Connected to IoT Stream'); + }); - socket.on('iot_update', (data) => { - setIotData(data); - }); + socket.on('iot_update', (data) => { + setIotData(data); + }); - socket.on('disconnect', () => { - setConnected(false); - }); + socket.on('disconnect', () => { + setConnected(false); + }); - return () => { - socket.disconnect(); - }; - }, []); + return () => { + socket.disconnect(); + }; + }, []); - return { iotData, connected }; + return { iotData, connected }; }; diff --git a/src/hooks/usePWA.js b/src/hooks/usePWA.js index 1e51fd3..4a8f8f5 100644 --- a/src/hooks/usePWA.js +++ b/src/hooks/usePWA.js @@ -1,52 +1,52 @@ import { useState, useEffect } from 'react'; export const usePWA = () => { - const [deferredPrompt, setDeferredPrompt] = useState(null); - const [isInstallable, setIsInstallable] = useState(false); - - useEffect(() => { - const handleBeforeInstallPrompt = (e) => { - // Prevent the mini-infobar from appearing on mobile - e.preventDefault(); - // Stash the event so it can be triggered later. - setDeferredPrompt(e); - // Update UI to notify the user they can install the PWA - setIsInstallable(true); - }; - - window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt); - - // Hide the button once installed successfully - window.addEventListener('appinstalled', () => { - setIsInstallable(false); - setDeferredPrompt(null); - console.log('PWA was installed successfully!'); - }); - - // Check if the app is already installed (standalone mode) - if (window.matchMedia('(display-mode: standalone)').matches) { - setIsInstallable(false); - } - - return () => { - window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt); - }; - }, []); - - const promptInstall = async () => { - if (!deferredPrompt) return; - - // Show the browser installation prompt - deferredPrompt.prompt(); - - // Wait for the user to respond to the prompt - const { outcome } = await deferredPrompt.userChoice; - console.log(`User response to the PWA install prompt: ${outcome}`); - - // The prompt can only be used once - setDeferredPrompt(null); - setIsInstallable(false); + const [deferredPrompt, setDeferredPrompt] = useState(null); + const [isInstallable, setIsInstallable] = useState(false); + + useEffect(() => { + const handleBeforeInstallPrompt = (e) => { + // Prevent the mini-infobar from appearing on mobile + e.preventDefault(); + // Stash the event so it can be triggered later. + setDeferredPrompt(e); + // Update UI to notify the user they can install the PWA + setIsInstallable(true); }; - return { isInstallable, promptInstall }; + window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt); + + // Hide the button once installed successfully + window.addEventListener('appinstalled', () => { + setIsInstallable(false); + setDeferredPrompt(null); + console.log('PWA was installed successfully!'); + }); + + // Check if the app is already installed (standalone mode) + if (window.matchMedia('(display-mode: standalone)').matches) { + setIsInstallable(false); + } + + return () => { + window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt); + }; + }, []); + + const promptInstall = async () => { + if (!deferredPrompt) return; + + // Show the browser installation prompt + deferredPrompt.prompt(); + + // Wait for the user to respond to the prompt + const { outcome } = await deferredPrompt.userChoice; + console.log(`User response to the PWA install prompt: ${outcome}`); + + // The prompt can only be used once + setDeferredPrompt(null); + setIsInstallable(false); + }; + + return { isInstallable, promptInstall }; }; diff --git a/src/index.css b/src/index.css index 94b1036..11f6923 100644 --- a/src/index.css +++ b/src/index.css @@ -49,4 +49,4 @@ body.dark { ::-webkit-scrollbar-thumb { @apply bg-slate-700/50 rounded-full hover:bg-slate-600; -} \ No newline at end of file +} diff --git a/src/main.jsx b/src/main.jsx index 16f64ba..222d08b 100644 --- a/src/main.jsx +++ b/src/main.jsx @@ -7,10 +7,10 @@ import { AppProvider } from './context/AppContext'; // Actively unregister any lingering service workers in dev/tunnel mode if ('serviceWorker' in navigator) { - navigator.serviceWorker.getRegistrations().then(registrations => { - for (let registration of registrations) { + navigator.serviceWorker.getRegistrations().then((registrations) => { + for (const registration of registrations) { registration.unregister(); - console.log("Unregistered a ghost service worker."); + console.log('Unregistered a ghost service worker.'); } }); } @@ -27,7 +27,7 @@ class ErrorBoundary extends React.Component { } componentDidCatch(error, errorInfo) { - console.error("React Error Boundary caught an error:", error, errorInfo); + console.error('React Error Boundary caught an error:', error, errorInfo); } render() { diff --git a/src/pages/AcceleratedAnalytics.jsx b/src/pages/AcceleratedAnalytics.jsx index 33dc56a..4765302 100644 --- a/src/pages/AcceleratedAnalytics.jsx +++ b/src/pages/AcceleratedAnalytics.jsx @@ -1,852 +1,1071 @@ import React, { useState, useEffect } from 'react'; -import { - Cpu, Database, Send, Sparkles, RefreshCw, Zap, Flame, - BarChart3, Cloud, Play, AlertTriangle, CheckCircle, Award, - Terminal, ArrowRight, Loader2, Info +import { + Cpu, + Database, + Send, + Sparkles, + RefreshCw, + Zap, + Flame, + BarChart3, + Cloud, + Play, + AlertTriangle, + CheckCircle, + Award, + Terminal, + ArrowRight, + Loader2, + Info, } from 'lucide-react'; -import { - ResponsiveContainer, AreaChart, Area, XAxis, YAxis, - CartesianGrid, Tooltip, Legend, BarChart, Bar +import { + ResponsiveContainer, + AreaChart, + Area, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + Legend, + BarChart, + Bar, } from 'recharts'; import { rapidsAnalyticsAPI } from '../services/api'; import { motion, AnimatePresence } from 'framer-motion'; // SQL Templates for BigQuery workbench const SQL_TEMPLATES = { - bottlenecks: `SELECT intersection_id, corridor, AVG(speed) AS speed_mph, AVG(volume) AS volume_vpm, AVG(congestion_risk) AS risk_index + bottlenecks: `SELECT intersection_id, corridor, AVG(speed) AS speed_mph, AVG(volume) AS volume_vpm, AVG(congestion_risk) AS risk_index FROM city_traffic.sensor_telemetry WHERE speed < 22 AND volume > 70 AND congestion_risk > 50 GROUP BY intersection_id, corridor ORDER BY risk_index DESC LIMIT 10;`, - corridors: `SELECT corridor, AVG(speed) AS avg_speed_mph, AVG(volume) AS avg_volume_vpm, AVG(congestion_risk) AS avg_risk_index, AVG(wait_time) AS avg_wait_sec + corridors: `SELECT corridor, AVG(speed) AS avg_speed_mph, AVG(volume) AS avg_volume_vpm, AVG(congestion_risk) AS avg_risk_index, AVG(wait_time) AS avg_wait_sec FROM city_traffic.sensor_telemetry GROUP BY corridor ORDER BY avg_risk_index DESC;`, - weather: `SELECT weather, AVG(speed) AS avg_speed_mph, AVG(volume) AS avg_volume_vpm, AVG(congestion_risk) AS avg_risk_index, AVG(wait_time) AS avg_wait_sec + weather: `SELECT weather, AVG(speed) AS avg_speed_mph, AVG(volume) AS avg_volume_vpm, AVG(congestion_risk) AS avg_risk_index, AVG(wait_time) AS avg_wait_sec FROM city_traffic.sensor_telemetry GROUP BY weather;`, - signals: `SELECT intersection_id, corridor, AVG(congestion_risk) AS avg_risk, MAX(signal_adjustment_sec) AS recommended_green_phase_ext_sec + signals: `SELECT intersection_id, corridor, AVG(congestion_risk) AS avg_risk, MAX(signal_adjustment_sec) AS recommended_green_phase_ext_sec FROM city_traffic.sensor_telemetry WHERE signal_adjustment_sec > 0 GROUP BY intersection_id, corridor ORDER BY recommended_green_phase_ext_sec DESC -LIMIT 8;` +LIMIT 8;`, }; const AcceleratedAnalytics = () => { - // State - const [analytics, setAnalytics] = useState(null); - const [benchmarks, setBenchmarks] = useState([]); - const [loading, setLoading] = useState(true); - const [benchmarking, setBenchmarking] = useState(false); - const [sqlQuery, setSqlQuery] = useState(SQL_TEMPLATES.bottlenecks); - const [queryResults, setQueryResults] = useState(null); - const [queryLoading, setQueryLoading] = useState(false); - const [queryPlan, setQueryPlan] = useState(null); - const [geminiPrompt, setGeminiPrompt] = useState('Synthesize a full traffic anomaly advisory and signal-timing tuning plan for today\'s rush hours.'); - const [geminiResponse, setGeminiResponse] = useState(''); - const [geminiLoading, setGeminiLoading] = useState(false); - const [selectedTemplate, setSelectedTemplate] = useState('bottlenecks'); - const [activeTab, setActiveTab] = useState('overview'); // overview, benchmark, sql, gemini - - // Fetch initial data - useEffect(() => { - fetchAnalyticsData(); - runMockQuery(SQL_TEMPLATES.bottlenecks); - }, []); - - const fetchAnalyticsData = async () => { - setLoading(true); - try { - const data = await rapidsAnalyticsAPI.getData(); - setAnalytics(data.analytics); - setBenchmarks(data.benchmarks); - } catch (error) { - console.error('Error fetching data:', error); - } finally { - setLoading(false); - } - }; - - const handleRunBenchmark = async () => { - setBenchmarking(true); - try { - const data = await rapidsAnalyticsAPI.runBenchmark(); - setAnalytics(data.analytics); - setBenchmarks(data.benchmarks); - } catch (error) { - console.error('Error running benchmark:', error); - alert('Failed to execute backend benchmark run.'); - } finally { - setBenchmarking(false); - } - }; - - const handleTemplateChange = (e) => { - const value = e.target.value; - setSelectedTemplate(value); - setSqlQuery(SQL_TEMPLATES[value]); - runMockQuery(SQL_TEMPLATES[value]); - }; - - const runMockQuery = async (queryText) => { - setQueryLoading(true); - setQueryPlan(null); - try { - const res = await rapidsAnalyticsAPI.query(queryText); - setQueryResults(res.results); - - // Generate simulated query plan details - setQueryPlan({ - bytesProcessed: '4.2 MB', - executionTime: `${(0.08 + Math.random() * 0.09).toFixed(3)}s`, - nodesUsed: 1, - acceleration: 'cuDF GPU Accelerated' - }); - } catch (error) { - console.error('Error running SQL query:', error); - setQueryResults([{ Error: 'Failed to connect to database query pipeline.' }]); - } finally { - setQueryLoading(false); - } - }; - - const handleExecuteSql = () => { - runMockQuery(sqlQuery); - }; - - const handleAskGemini = async (presetPrompt = null) => { - const targetPrompt = presetPrompt || geminiPrompt; - if (!targetPrompt.trim()) return; - - setGeminiLoading(true); - setGeminiResponse(''); - try { - // Compile context for Gemini to read - const dataContext = { - corridors: analytics?.corridors || [], - bottlenecks: analytics?.bottlenecks || [], - totalRowsCount: analytics?.totalRows || 100000, - hardware: analytics?.hardware || 'CPU (Standard Pandas)' - }; - - const res = await rapidsAnalyticsAPI.askGemini(targetPrompt, dataContext); - setGeminiResponse(res.response); - } catch (error) { - console.error('Error asking Gemini:', error); - setGeminiResponse('⚠️ Error communicating with Gemini Enterprise Agent. Please check backend environment variables or connection status.'); - } finally { - setGeminiLoading(false); - } - }; - - // Formatter helpers - const formatNumber = (num) => { - if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'; - if (num >= 1000) return (num / 1000).toFixed(0) + 'K'; - return num; - }; - - // Custom tooltips - const BenchmarkTooltip = ({ active, payload }) => { - if (active && payload && payload.length) { - const data = payload[0].payload; - return ( -
-

Data Size: {formatNumber(data.size)} rows

-

Pandas CPU: {data.cpuTimeMs.toFixed(1)} ms

-

cuDF GPU: {data.gpuTimeMs.toFixed(2)} ms

-

Speedup: {data.speedupFactor}x faster

-
- ); - } - return null; - }; - - if (loading) { - return ( -
- -

Ingesting BigQuery telemetry and compiling RAPIDS indices...

-
- ); + // State + const [analytics, setAnalytics] = useState(null); + const [benchmarks, setBenchmarks] = useState([]); + const [loading, setLoading] = useState(true); + const [benchmarking, setBenchmarking] = useState(false); + const [sqlQuery, setSqlQuery] = useState(SQL_TEMPLATES.bottlenecks); + const [queryResults, setQueryResults] = useState(null); + const [queryLoading, setQueryLoading] = useState(false); + const [queryPlan, setQueryPlan] = useState(null); + const [geminiPrompt, setGeminiPrompt] = useState( + "Synthesize a full traffic anomaly advisory and signal-timing tuning plan for today's rush hours." + ); + const [geminiResponse, setGeminiResponse] = useState(''); + const [geminiLoading, setGeminiLoading] = useState(false); + const [selectedTemplate, setSelectedTemplate] = useState('bottlenecks'); + const [activeTab, setActiveTab] = useState('overview'); // overview, benchmark, sql, gemini + + // Fetch initial data + useEffect(() => { + fetchAnalyticsData(); + runMockQuery(SQL_TEMPLATES.bottlenecks); + }, []); + + const fetchAnalyticsData = async () => { + setLoading(true); + try { + const data = await rapidsAnalyticsAPI.getData(); + setAnalytics(data.analytics); + setBenchmarks(data.benchmarks); + } catch (error) { + console.error('Error fetching data:', error); + } finally { + setLoading(false); } + }; + const handleRunBenchmark = async () => { + setBenchmarking(true); + try { + const data = await rapidsAnalyticsAPI.runBenchmark(); + setAnalytics(data.analytics); + setBenchmarks(data.benchmarks); + } catch (error) { + console.error('Error running benchmark:', error); + alert('Failed to execute backend benchmark run.'); + } finally { + setBenchmarking(false); + } + }; + + const handleTemplateChange = (e) => { + const value = e.target.value; + setSelectedTemplate(value); + setSqlQuery(SQL_TEMPLATES[value]); + runMockQuery(SQL_TEMPLATES[value]); + }; + + const runMockQuery = async (queryText) => { + setQueryLoading(true); + setQueryPlan(null); + try { + const res = await rapidsAnalyticsAPI.query(queryText); + setQueryResults(res.results); + + // Generate simulated query plan details + setQueryPlan({ + bytesProcessed: '4.2 MB', + executionTime: `${(0.08 + Math.random() * 0.09).toFixed(3)}s`, + nodesUsed: 1, + acceleration: 'cuDF GPU Accelerated', + }); + } catch (error) { + console.error('Error running SQL query:', error); + setQueryResults([{ Error: 'Failed to connect to database query pipeline.' }]); + } finally { + setQueryLoading(false); + } + }; + + const handleExecuteSql = () => { + runMockQuery(sqlQuery); + }; + + const handleAskGemini = async (presetPrompt = null) => { + const targetPrompt = presetPrompt || geminiPrompt; + if (!targetPrompt.trim()) return; + + setGeminiLoading(true); + setGeminiResponse(''); + try { + // Compile context for Gemini to read + const dataContext = { + corridors: analytics?.corridors || [], + bottlenecks: analytics?.bottlenecks || [], + totalRowsCount: analytics?.totalRows || 100000, + hardware: analytics?.hardware || 'CPU (Standard Pandas)', + }; + + const res = await rapidsAnalyticsAPI.askGemini(targetPrompt, dataContext); + setGeminiResponse(res.response); + } catch (error) { + console.error('Error asking Gemini:', error); + setGeminiResponse( + '⚠️ Error communicating with Gemini Enterprise Agent. Please check backend environment variables or connection status.' + ); + } finally { + setGeminiLoading(false); + } + }; + + // Formatter helpers + const formatNumber = (num) => { + if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'; + if (num >= 1000) return (num / 1000).toFixed(0) + 'K'; + return num; + }; + + // Custom tooltips + const BenchmarkTooltip = ({ active, payload }) => { + if (active && payload && payload.length) { + const data = payload[0].payload; + return ( +
+

Data Size: {formatNumber(data.size)} rows

+

+ Pandas CPU: {data.cpuTimeMs.toFixed(1)} ms +

+

+ cuDF GPU: {data.gpuTimeMs.toFixed(2)} ms +

+

+ Speedup: {data.speedupFactor}x faster +

+
+ ); + } + return null; + }; + + if (loading) { return ( -
- {/* Header section */} -
-
-
- - NVIDIA RAPIDS - - - Google BigQuery - -
-

- RAPIDS & BigQuery Traffic Intelligence -

-

- Accelerated decision-support pipeline for urban traffic control and signal autopilot. -

-
+
+ +

+ Ingesting BigQuery telemetry and compiling RAPIDS indices... +

+
+ ); + } - {/* Network nodes indicators */} -
-
- - GCS Bucket: CONNECTED -
-
- - GPU Unit: NVIDIA L4 -
-
+ return ( +
+ {/* Header section */} +
+
+
+ + NVIDIA RAPIDS + + + Google BigQuery + +
+

+ RAPIDS & BigQuery Traffic Intelligence +

+

+ Accelerated decision-support pipeline for urban traffic control and signal autopilot. +

+
+ + {/* Network nodes indicators */} +
+
+ + + GCS Bucket: CONNECTED + +
+
+ + + GPU Unit: NVIDIA L4 + +
+
+
+ + {/* Pipeline Workflow Visualizer */} +
+

+ + Accelerated Data Ingestion & Analytics Pipeline +

+
+
+
+
+
+

+ 1. Ingest +

+

+ IoT Telemetry +

+

10K logs/sec

+
+
- {/* Pipeline Workflow Visualizer */} -
-

- - Accelerated Data Ingestion & Analytics Pipeline -

-
- -
-
- -
-
-

1. Ingest

-

IoT Telemetry

-

10K logs/sec

+
+ +
+ +
+
+ +
+
+

+ 2. Warehouse +

+

+ GCS & BigQuery +

+

city_traffic.telemetry

+
+
+ +
+ +
+ +
+
+ +
+
+ +
+
+

+ 3. Process +

+

+ NVIDIA cuDF +

+

+ 85x Acceleration +

+
+
+
+
+ + {/* TAB Navigation */} +
+ + + + +
+ + {/* TAB PANELS */} +
+ {/* 1. OVERVIEW & CORRIDOR TUNING TAB */} + {activeTab === 'overview' && ( +
+ {/* Summary Metrics */} +
+
+

+ Active Records Ingested +

+

+ {analytics?.totalRows ? analytics.totalRows.toLocaleString() : '100,000'} +

+ + From GCS Loop Telemetry + + +
+ +
+

+ RAPIDS Execution Time +

+

+ {(analytics?.metrics?.totalTimeSec + ? analytics.metrics.totalTimeSec * 1000 + : 328.8 + ).toFixed(1)}{' '} + ms +

+ + 98.8% faster than Pandas CPU + + +
+ +
+

+ Active Gridlocks detected +

+

+ {analytics?.bottlenecks?.length || 0} +

+ + Critical bottleneck intersections + + +
+ +
+

+ Avg Gridlock Risk Score +

+

+ {analytics?.corridors + ? ( + analytics.corridors.reduce((acc, c) => acc + c.congestionRisk, 0) / + analytics.corridors.length + ).toFixed(1) + : '0'} + % +

+ + Surge Pricing activated on 2 zones + + +
+
+ + {/* Corridor Tuning & Recommendations Grid */} +
+ {/* Corridor Status List */} +
+
+

+ + Corridor Congestion & Adaptations +

+ + Last updated:{' '} + {analytics?.timestamp + ? new Date(analytics.timestamp).toLocaleTimeString() + : 'Live'} + +
+ +
+ {analytics?.corridors?.map((corridor, i) => { + let riskColor = 'bg-brand-green'; + let riskText = 'text-brand-green'; + if (corridor.congestionRisk > 60) { + riskColor = 'bg-brand-red'; + riskText = 'text-brand-red'; + } else if (corridor.congestionRisk > 40) { + riskColor = 'bg-brand-yellow'; + riskText = 'text-brand-yellow'; + } + + return ( +
+
+
+

+ {corridor.name} +

+
+ + Avg Speed:{' '} + + {corridor.avgSpeed} mph + + + + Flow Vol:{' '} + + {corridor.avgVolume} vpm + + + + Wait:{' '} + + {corridor.avgWaitTime}s + + +
+
+ +
+ + {corridor.congestionRisk.toFixed(0)}% Risk + + + Est. CO2: {corridor.co2EmissionsKg} kg/h + +
-
- -
- -
-
-
- +
+
+
+
+ + {corridor.recommendedTuning > 0 ? ( + + Add {corridor.recommendedTuning}s Green + + ) : ( + + Signal Sync OK + + )}
+
+ ); + })} +
+
+ + {/* Bottleneck Intersections Card */} +
+
+

+ + Top Bottleneck Junctions +

+

+ Identified as having speeds below 22 mph, vehicle occupancy exceeding 75%, and + wait times above 60s. +

+ +
+ {analytics?.bottlenecks?.map((bot, i) => ( +
-

2. Warehouse

-

GCS & BigQuery

-

city_traffic.telemetry

+

+ {bot.intersectionId} +

+

+ {bot.corridor.split(' ')[0]} corridor +

+
+
+ + {bot.congestionRisk.toFixed(0)}% Risk + + + Suggest: +{bot.recommendedTuning}s +
+
+ ))} +
+
+ +
+
+ +
+

Auto-Tuning Benefits

+

+ NVIDIA-accelerated autopilot offsets cut loop latency by 95%, saving an + estimated 320 Gallons of fuel daily across these intersections. +

+
+
+
+
+
+ )} + + {/* 2. NVIDIA RAPIDS BENCHMARKS TAB */} + {activeTab === 'benchmark' && ( +
+
+ {/* Performance Chart Card */} +
+
+
+

+ + Data scale vs Processing Speed (log scale) +

+

+ Comparing standard Pandas CPU execution vs GPU-Accelerated NVIDIA RAPIDS cuDF. +

+
-
- + +
+ +
+ + + + + + + + + + + + + + + + } /> + + + + + +
+
+ + {/* Benchmark Details Card */} +
+
+

+ Performance Insights +

+ +
+
+
+

+ Max Acceleration +

+

93.3x

+
+
-
-
- -
-
- -
-
-

3. Process

-

NVIDIA cuDF

-

- 85x Acceleration -

-
+
+
+

+ GPU Throughput +

+

+ 36.3M rows/sec +

+
+
+
+
+ + Why cuDF is essential here: + + Traffic loops in large metropolitan networks generate millions of telemetry + updates daily. Re-calculating adaptive corridor signals using standard + single-threaded CPU libraries introduces severe bottlenecks. By offloading + vectorized operations to an **NVIDIA GPU**, our update cycle latency drops from + **25.6 seconds** to just **275 milliseconds** for 10 million rows, making + adaptive autopilot feasible in real time. +
-
- {/* TAB Navigation */} -
- - - - +
+ + + Benchmark is running locally using cuDF simulator. Natively executes on CUDA + hardware. + +
+
+
+ )} - {/* TAB PANELS */} -
- {/* 1. OVERVIEW & CORRIDOR TUNING TAB */} - {activeTab === 'overview' && ( -
- {/* Summary Metrics */} -
-
-

Active Records Ingested

-

{analytics?.totalRows ? analytics.totalRows.toLocaleString() : '100,000'}

- From GCS Loop Telemetry - -
- -
-

RAPIDS Execution Time

-

- {(analytics?.metrics?.totalTimeSec ? analytics.metrics.totalTimeSec * 1000 : 328.8).toFixed(1)} ms -

- 98.8% faster than Pandas CPU - -
+ {/* 3. BIGQUERY SQL CONSOLE TAB */} + {activeTab === 'sql' && ( +
+
+ {/* Editor card */} +
+
+

+ + Google Cloud BigQuery SQL Workbench +

-
-

Active Gridlocks detected

-

{analytics?.bottlenecks?.length || 0}

- Critical bottleneck intersections - -
+
+ Template: + +
+
-
-

Avg Gridlock Risk Score

-

- {analytics?.corridors ? (analytics.corridors.reduce((acc, c) => acc + c.congestionRisk, 0) / analytics.corridors.length).toFixed(1) : '0'}% -

- Surge Pricing activated on 2 zones - -
-
+
+
+ SQL Standard +
+