From e220f73b6f0c2e4a17565ac59bdf013f661aa6c6 Mon Sep 17 00:00:00 2001 From: FlashL3opard <69573060+Flashl3opard@users.noreply.github.com> Date: Thu, 23 Jul 2026 14:03:53 +0530 Subject: [PATCH] PHEE-379: implement in-app Keycloak auth using ROPC flow --- package-lock.json | 256 ++++++++++++++ package.json | 3 + src/components/shared/AppLayout.tsx | 56 +++- src/lib/api/client.ts | 8 +- src/lib/exportCsv.ts | 26 ++ src/lib/exportPdf.ts | 30 ++ src/lib/keycloak/KeycloakProvider.tsx | 90 +++++ src/lib/keycloak/keycloak.ts | 9 + src/lib/keycloak/useAuth.ts | 35 ++ src/main.tsx | 47 ++- .../account-mapper/SelfServicePortal.tsx | 315 ++++++++++++++++++ src/modules/auth/Login.tsx | 52 ++- src/modules/payment-hub/MainBatchesTab.tsx | 35 +- src/modules/payment-hub/SubBatchesTab.tsx | 35 +- src/modules/payment-hub/TransfersTab.tsx | 37 +- src/pages/AccountMapperSelfService.tsx | 1 + 16 files changed, 1001 insertions(+), 34 deletions(-) create mode 100644 src/lib/exportCsv.ts create mode 100644 src/lib/exportPdf.ts create mode 100644 src/lib/keycloak/KeycloakProvider.tsx create mode 100644 src/lib/keycloak/keycloak.ts create mode 100644 src/lib/keycloak/useAuth.ts create mode 100644 src/modules/account-mapper/SelfServicePortal.tsx create mode 100644 src/pages/AccountMapperSelfService.tsx diff --git a/package-lock.json b/package-lock.json index 02d0138..54478df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,9 @@ "axios": "^1.18.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "jspdf": "^4.2.1", + "jspdf-autotable": "^5.0.8", + "keycloak-js": "^26.2.4", "lucide-react": "^1.18.0", "radix-ui": "^1.5.0", "react": "^19.2.6", @@ -399,6 +402,15 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", @@ -3201,6 +3213,19 @@ "undici-types": "~7.18.0" } }, + "node_modules/@types/pako": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz", + "integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==", + "license": "MIT" + }, + "node_modules/@types/raf": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz", + "integrity": "sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==", + "license": "MIT", + "optional": true + }, "node_modules/@types/react": { "version": "19.2.17", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz", @@ -3221,6 +3246,13 @@ "@types/react": "^19.2.0" } }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, "node_modules/@types/validate-npm-package-name": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/validate-npm-package-name/-/validate-npm-package-name-4.0.2.tgz", @@ -3700,6 +3732,16 @@ "node": "18 || 20 || >=22" } }, + "node_modules/base64-arraybuffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz", + "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6.0" + } + }, "node_modules/baseline-browser-mapping": { "version": "2.10.37", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.37.tgz", @@ -3888,6 +3930,26 @@ ], "license": "CC-BY-4.0" }, + "node_modules/canvg": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/canvg/-/canvg-3.0.11.tgz", + "integrity": "sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@babel/runtime": "^7.12.5", + "@types/raf": "^3.4.0", + "core-js": "^3.8.3", + "raf": "^3.4.1", + "regenerator-runtime": "^0.13.7", + "rgbcolor": "^1.0.1", + "stackblur-canvas": "^2.0.0", + "svg-pathdata": "^6.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/chalk": { "version": "5.6.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", @@ -4025,6 +4087,18 @@ "node": ">=6.6.0" } }, + "node_modules/core-js": { + "version": "3.49.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.49.0.tgz", + "integrity": "sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, "node_modules/cors": { "version": "2.8.6", "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", @@ -4082,6 +4156,16 @@ "node": ">= 8" } }, + "node_modules/css-line-break": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/css-line-break/-/css-line-break-2.1.0.tgz", + "integrity": "sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==", + "license": "MIT", + "optional": true, + "dependencies": { + "utrie": "^1.0.2" + } + }, "node_modules/cssesc": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", @@ -4239,6 +4323,16 @@ "node": ">=0.3.1" } }, + "node_modules/dompurify": { + "version": "3.4.12", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.12.tgz", + "integrity": "sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optional": true, + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/dotenv": { "version": "17.4.2", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", @@ -4823,6 +4917,17 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-png": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/fast-png/-/fast-png-6.4.0.tgz", + "integrity": "sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==", + "license": "MIT", + "dependencies": { + "@types/pako": "^2.0.3", + "iobuffer": "^5.3.2", + "pako": "^2.1.0" + } + }, "node_modules/fast-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", @@ -4888,6 +4993,12 @@ "node": "^12.20 || >= 14.13" } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, "node_modules/figures": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", @@ -5300,6 +5411,20 @@ "node": ">=16.9.0" } }, + "node_modules/html2canvas": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz", + "integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==", + "license": "MIT", + "optional": true, + "dependencies": { + "css-line-break": "^2.1.0", + "text-segmentation": "^1.0.3" + }, + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -5399,6 +5524,12 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/iobuffer": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz", + "integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==", + "license": "MIT" + }, "node_modules/ip-address": { "version": "10.2.0", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", @@ -5712,6 +5843,41 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jspdf": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.2.1.tgz", + "integrity": "sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.6", + "fast-png": "^6.2.0", + "fflate": "^0.8.1" + }, + "optionalDependencies": { + "canvg": "^3.0.11", + "core-js": "^3.6.0", + "dompurify": "^3.3.1", + "html2canvas": "^1.0.0-rc.5" + } + }, + "node_modules/jspdf-autotable": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/jspdf-autotable/-/jspdf-autotable-5.0.8.tgz", + "integrity": "sha512-Hy05N86yBO7CXBrnSLOge7i1ZYpKH2DjQ94iybaP7vBhSInjvRBgDc99ngKzSbSO8Jc98ZCally8I6n0tj2RJQ==", + "license": "MIT", + "peerDependencies": { + "jspdf": "^2 || ^3 || ^4" + } + }, + "node_modules/keycloak-js": { + "version": "26.2.4", + "resolved": "https://registry.npmjs.org/keycloak-js/-/keycloak-js-26.2.4.tgz", + "integrity": "sha512-PnXpR3ubETGOt0B/Qt2lxmPbkZr5bc3vlQsOqDoTPPQsZRp7JjhTKxlJ187uWh8qJhvBab6Gsjb06a8ayOPfuw==", + "license": "Apache-2.0", + "workspaces": [ + "test" + ] + }, "node_modules/keyv": { "version": "4.5.4", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", @@ -6508,6 +6674,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/pako": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz", + "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "(MIT AND Zlib)" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -6594,6 +6776,13 @@ "url": "https://opencollective.com/express" } }, + "node_modules/performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==", + "license": "MIT", + "optional": true + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -6865,6 +7054,16 @@ } } }, + "node_modules/raf": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz", + "integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==", + "license": "MIT", + "optional": true, + "dependencies": { + "performance-now": "^2.1.0" + } + }, "node_modules/range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -7033,6 +7232,13 @@ "node": ">= 4" } }, + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "license": "MIT", + "optional": true + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -7077,6 +7283,16 @@ "node": ">=0.10.0" } }, + "node_modules/rgbcolor": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/rgbcolor/-/rgbcolor-1.0.1.tgz", + "integrity": "sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==", + "license": "MIT OR SEE LICENSE IN FEEL-FREE.md", + "optional": true, + "engines": { + "node": ">= 0.8.15" + } + }, "node_modules/rolldown": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz", @@ -7468,6 +7684,16 @@ "node": ">=0.10.0" } }, + "node_modules/stackblur-canvas": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.7.0.tgz", + "integrity": "sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.1.14" + } + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -7583,6 +7809,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/svg-pathdata": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/svg-pathdata/-/svg-pathdata-6.0.3.tgz", + "integrity": "sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/tailwind-merge": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.6.0.tgz", @@ -7612,6 +7848,16 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/text-segmentation": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/text-segmentation/-/text-segmentation-1.0.3.tgz", + "integrity": "sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==", + "license": "MIT", + "optional": true, + "dependencies": { + "utrie": "^1.0.2" + } + }, "node_modules/tiny-invariant": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", @@ -7940,6 +8186,16 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, + "node_modules/utrie": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/utrie/-/utrie-1.0.2.tgz", + "integrity": "sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==", + "license": "MIT", + "optional": true, + "dependencies": { + "base64-arraybuffer": "^1.0.2" + } + }, "node_modules/validate-npm-package-name": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-7.0.2.tgz", diff --git a/package.json b/package.json index 3667bc6..c29ca93 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,9 @@ "axios": "^1.18.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", + "jspdf": "^4.2.1", + "jspdf-autotable": "^5.0.8", + "keycloak-js": "^26.2.4", "lucide-react": "^1.18.0", "radix-ui": "^1.5.0", "react": "^19.2.6", diff --git a/src/components/shared/AppLayout.tsx b/src/components/shared/AppLayout.tsx index 24ce958..8eb3983 100644 --- a/src/components/shared/AppLayout.tsx +++ b/src/components/shared/AppLayout.tsx @@ -1,5 +1,5 @@ import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom' -import { useState } from 'react' +import { useState, useRef, useEffect } from 'react' import type { LucideIcon } from 'lucide-react' import { ArrowLeftRight, @@ -9,6 +9,7 @@ import { HelpCircle, LayoutDashboard, Landmark, + LogOut, Search, Settings, Shield, @@ -18,6 +19,7 @@ import { Users, } from 'lucide-react' import { APP_NAME, DEFAULT_TENANT, TENANTS } from '@/config/constants' +import { useAuth } from '@/lib/keycloak/useAuth' interface NavItem { label: string @@ -42,15 +44,29 @@ const navItems: NavItem[] = [ export default function AppLayout() { const location = useLocation() const navigate = useNavigate() + const { user, logout } = useAuth() const [tenant, setTenant] = useState( localStorage.getItem('tenant') ?? DEFAULT_TENANT ) + const [avatarOpen, setAvatarOpen] = useState(false) + const avatarRef = useRef(null) function handleTenantChange(value: string) { setTenant(value) localStorage.setItem('tenant', value) } + // Close dropdown on outside click + useEffect(() => { + function handleClick(e: MouseEvent) { + if (avatarRef.current && !avatarRef.current.contains(e.target as Node)) { + setAvatarOpen(false) + } + } + document.addEventListener('mousedown', handleClick) + return () => document.removeEventListener('mousedown', handleClick) + }, []) + function isActive(item: NavItem) { return item.exact ? location.pathname === item.path @@ -138,8 +154,42 @@ export default function AppLayout() { -
- + {/* Avatar dropdown */} +
+ + + {avatarOpen && ( +
+ {user && ( +
+

{user.name}

+

{user.email}

+
+ )} + +
+ )}
diff --git a/src/lib/api/client.ts b/src/lib/api/client.ts index fac8e6e..c1f2bb9 100644 --- a/src/lib/api/client.ts +++ b/src/lib/api/client.ts @@ -6,7 +6,13 @@ const apiClient = axios.create({ apiClient.interceptors.request.use((config) => { const tenant = localStorage.getItem('tenant') || 'greenbank' - config.headers.set('X-TenantId', tenant) + config.headers.set('Platform-TenantId', tenant) + + const token = localStorage.getItem('kc_token') + if (token) { + config.headers.set('Authorization', `Bearer ${token}`) + } + return config }) diff --git a/src/lib/exportCsv.ts b/src/lib/exportCsv.ts new file mode 100644 index 0000000..bec2964 --- /dev/null +++ b/src/lib/exportCsv.ts @@ -0,0 +1,26 @@ +export function exportCsv(rows: Record[], filename: string) { + if (rows.length === 0) return + const headers = Object.keys(rows[0]) + const escape = (v: unknown) => { + const s = v == null ? '' : String(v) + return s.includes(',') || s.includes('"') || s.includes('\n') + ? `"${s.replace(/"/g, '""')}"` + : s + } + const csv = [ + headers.join(','), + ...rows.map((r) => headers.map((h) => escape(r[h])).join(',')), + ].join('\n') + + const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }) + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = filename + a.click() + URL.revokeObjectURL(url) +} + +export function csvDate() { + return new Date().toISOString().slice(0, 10) +} diff --git a/src/lib/exportPdf.ts b/src/lib/exportPdf.ts new file mode 100644 index 0000000..4003e67 --- /dev/null +++ b/src/lib/exportPdf.ts @@ -0,0 +1,30 @@ +import { jsPDF } from 'jspdf' +import autoTable from 'jspdf-autotable' +import { csvDate } from './exportCsv' + +export function exportPdf( + title: string, + headers: string[], + rows: (string | number)[][], + filename: string, +) { + const doc = new jsPDF({ orientation: 'landscape', unit: 'pt', format: 'a4' }) + doc.setFontSize(13) + doc.text(title, 40, 36) + doc.setFontSize(9) + doc.setTextColor(120) + doc.text(`Generated ${csvDate()}`, 40, 52) + + autoTable(doc, { + head: [headers], + body: rows as string[][], + startY: 64, + styles: { fontSize: 8, cellPadding: 4 }, + headStyles: { fillColor: [21, 101, 192], textColor: 255, fontStyle: 'bold' }, + alternateRowStyles: { fillColor: [245, 247, 250] }, + }) + + doc.save(filename) +} + +export { csvDate } diff --git a/src/lib/keycloak/KeycloakProvider.tsx b/src/lib/keycloak/KeycloakProvider.tsx new file mode 100644 index 0000000..6d46876 --- /dev/null +++ b/src/lib/keycloak/KeycloakProvider.tsx @@ -0,0 +1,90 @@ +import { createContext, useContext, useEffect, useState, type ReactNode } from 'react' +import { useNavigate } from 'react-router-dom' +import keycloak from './keycloak' + +interface KeycloakContextValue { + keycloak: typeof keycloak + authenticated: boolean + token: string | undefined + logout: () => void +} + +const KeycloakContext = createContext(null) + +export function useKeycloak() { + const ctx = useContext(KeycloakContext) + if (!ctx) throw new Error('useKeycloak must be used inside KeycloakProvider') + return ctx +} + +export default function KeycloakProvider({ children }: { children: ReactNode }) { + const navigate = useNavigate() + const [initialized, setInitialized] = useState(false) + const [authenticated, setAuthenticated] = useState(false) + + useEffect(() => { + if (keycloak.didInitialize) { + setAuthenticated(keycloak.authenticated ?? false) + if (keycloak.token) localStorage.setItem('kc_token', keycloak.token) + setInitialized(true) + return + } + + keycloak + .init({ + onLoad: 'check-sso', + checkLoginIframe: false, + pkceMethod: 'S256', + }) + .then((auth) => { + console.log('Auth status:', auth) + setAuthenticated(auth) + if (auth && keycloak.token) { + localStorage.setItem('kc_token', keycloak.token) + } else { + localStorage.removeItem('kc_token') + navigate('/login', { replace: true }) + } + setInitialized(true) + }) + .catch((err) => { + console.error('Keycloak init error:', err) + setInitialized(true) + navigate('/login', { replace: true }) + }) + + keycloak.onTokenExpired = () => { + keycloak.updateToken(60).then((refreshed) => { + if (refreshed && keycloak.token) { + localStorage.setItem('kc_token', keycloak.token) + } + }).catch(() => { + localStorage.removeItem('kc_token') + keycloak.logout() + }) + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + function logout() { + localStorage.removeItem('kc_token') + keycloak.logout({ redirectUri: `${window.location.origin}/login` }) + } + + if (!initialized) { + return ( +
+
+
+

Initializing session…

+
+
+ ) + } + + return ( + + {children} + + ) +} diff --git a/src/lib/keycloak/keycloak.ts b/src/lib/keycloak/keycloak.ts new file mode 100644 index 0000000..663e08c --- /dev/null +++ b/src/lib/keycloak/keycloak.ts @@ -0,0 +1,9 @@ +import Keycloak from 'keycloak-js' + +const keycloak = new Keycloak({ + url: import.meta.env.VITE_KEYCLOAK_URL, + realm: import.meta.env.VITE_KEYCLOAK_REALM, + clientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID, +}) + +export default keycloak diff --git a/src/lib/keycloak/useAuth.ts b/src/lib/keycloak/useAuth.ts new file mode 100644 index 0000000..c09d292 --- /dev/null +++ b/src/lib/keycloak/useAuth.ts @@ -0,0 +1,35 @@ +import { useKeycloak } from './KeycloakProvider' + +interface AuthUser { + name: string + email: string + username: string +} + +interface UseAuthReturn { + authenticated: boolean + token: string | undefined + user: AuthUser | null + logout: () => void + hasRole: (role: string) => boolean +} + +export function useAuth(): UseAuthReturn { + const { keycloak, authenticated, token, logout } = useKeycloak() + + const tokenParsed = keycloak.tokenParsed as Record | undefined + + const user: AuthUser | null = tokenParsed + ? { + name: (tokenParsed['name'] as string) ?? (tokenParsed['preferred_username'] as string) ?? '', + email: (tokenParsed['email'] as string) ?? '', + username: (tokenParsed['preferred_username'] as string) ?? '', + } + : null + + function hasRole(role: string): boolean { + return keycloak.hasRealmRole(role) || keycloak.hasResourceRole(role) + } + + return { authenticated, token, user, logout, hasRole } +} diff --git a/src/main.tsx b/src/main.tsx index fb93517..3cad75a 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,8 +1,9 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' -import { createBrowserRouter, RouterProvider } from 'react-router-dom' +import { createBrowserRouter, RouterProvider, Outlet } from 'react-router-dom' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import './index.css' +import KeycloakProvider from '@/lib/keycloak/KeycloakProvider' import AppLayout from '@/components/shared/AppLayout' import SplashScreen from '@/pages/SplashScreen' import LoginPage from '@/pages/LoginPage' @@ -16,28 +17,48 @@ import RBACConfig from '@/pages/RBACConfig' import Reporting from '@/pages/Reporting' import Visualizations from '@/pages/Visualizations' import NotFound from '@/pages/NotFound' +import AccountMapperSelfService from '@/pages/AccountMapperSelfService' + +// Thin root wrapper: supplies KeycloakProvider inside the router tree +// so useNavigate is available to the provider. +function AuthRoot() { + return ( + + + + ) +} const queryClient = new QueryClient() const router = createBrowserRouter([ + // Public routes — no Keycloak wrapper (Keycloak handles its own redirect) { path: '/splash', element: }, { path: '/login', element: }, + { path: '/account-mapper/self-service', element: }, + + // Protected routes — wrapped by KeycloakProvider { - path: '/', - element: , + element: , children: [ - { index: true, element: }, - { path: 'payment-hub', element: }, - { path: 'vouchers', element: }, - { path: 'account-mapper', element: }, - { path: 'g2p-config', element: }, - { path: 'settings', element: }, - { path: 'rbac', element: }, - { path: 'reporting', element: }, - { path: 'visualizations', element: }, + { + path: '/', + element: , + children: [ + { index: true, element: }, + { path: 'payment-hub', element: }, + { path: 'vouchers', element: }, + { path: 'account-mapper', element: }, + { path: 'g2p-config', element: }, + { path: 'settings', element: }, + { path: 'rbac', element: }, + { path: 'reporting', element: }, + { path: 'visualizations', element: }, + ], + }, + { path: '*', element: }, ], }, - { path: '*', element: }, ]) createRoot(document.getElementById('root')!).render( diff --git a/src/modules/account-mapper/SelfServicePortal.tsx b/src/modules/account-mapper/SelfServicePortal.tsx new file mode 100644 index 0000000..11ab645 --- /dev/null +++ b/src/modules/account-mapper/SelfServicePortal.tsx @@ -0,0 +1,315 @@ +import React, { useState } from 'react' +import { Link } from 'react-router-dom' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Button } from '@/components/ui/button' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { CheckCircle, AlertCircle, UserCircle } from 'lucide-react' + +const PAYMENT_MODALITIES = [ + '(01) Mobile Money', + '(02) Voucher', + '(03) Digital Wallet', + '(04) Bank Account', +] + +const FINANCIAL_INSTITUTIONS = [ + 'GreenBank', + 'BlueBank', + 'RedBank', + 'HDFC', + 'SBI', + 'DigiWallet', + 'VoucherFSP', +] + +interface FormState { + functionalId: string + fullName: string + financialInstitution: string + financialAddress: string + paymentModality: string + confirmAddress: string +} + +const empty: FormState = { + functionalId: '', + fullName: '', + financialInstitution: '', + financialAddress: '', + paymentModality: '', + confirmAddress: '', +} + +type Step = 'lookup' | 'update' | 'success' + +export default function SelfServicePortal() { + const [step, setStep] = useState('lookup') + const [form, setForm] = useState(empty) + const [lookupId, setLookupId] = useState('') + const [lookupError, setLookupError] = useState(false) + + function set(field: keyof FormState, value: string) { + setForm((prev) => ({ ...prev, [field]: value })) + } + + function handleLookup(e: React.FormEvent) { + e.preventDefault() + // Simulate lookup: any non-empty ID that starts with "BEN-" is found + if (lookupId.trim().toUpperCase().startsWith('BEN-')) { + setLookupError(false) + setForm((prev) => ({ ...prev, functionalId: lookupId.trim().toUpperCase() })) + setStep('update') + } else { + setLookupError(true) + } + } + + function handleSubmit(e: React.FormEvent) { + e.preventDefault() + if (form.financialAddress !== form.confirmAddress) return + setStep('success') + } + + function handleReset() { + setStep('lookup') + setLookupId('') + setLookupError(false) + setForm(empty) + } + + const mismatch = form.confirmAddress.length > 0 && form.financialAddress !== form.confirmAddress + + return ( +
+ {/* Top bar */} +
+
+ Payment Hub EE +
+ + ← Back to Admin + +
+ +
+
+ + {/* Step 1 — Lookup */} + {step === 'lookup' && ( +
+
+
+
+
+ +
+

Update Your Account

+

+ Enter your Functional ID to look up your record and update your financial account details. +

+
+ +
+
+ + { setLookupId(e.target.value); setLookupError(false) }} + required + /> + {lookupError && ( +

+ + No record found for this ID. Please check and try again. +

+ )} +
+ +
+ +

+ Your Functional ID is provided by your government programme administrator. +

+
+
+ )} + + {/* Step 2 — Update form */} + {step === 'update' && ( +
+
+
+
+

Update Account Details

+

+ Record found for {form.functionalId}. Fill in your updated details below. +

+
+ +
+
+ + set('fullName', e.target.value)} + required + /> +
+ +
+ + +
+ +
+ + +
+ +
+ + set('financialAddress', e.target.value)} + required + /> +

+ Enter your account number, registered mobile number, or wallet identifier. +

+
+ +
+ + set('confirmAddress', e.target.value)} + required + className={mismatch ? 'border-red-400 focus-visible:ring-red-300' : ''} + /> + {mismatch && ( +

+ + Financial addresses do not match. +

+ )} +
+ +
+ + +
+
+
+
+ )} + + {/* Step 3 — Success */} + {step === 'success' && ( +
+
+
+
+
+ +
+
+

Request Submitted

+

+ Your account update request has been received. Changes will be reviewed and applied within 1–2 business days. +

+
+
+ Functional ID + {form.functionalId} +
+
+ Institution + {form.financialInstitution} +
+
+ Modality + {form.paymentModality} +
+
+ +
+
+ )} +
+
+ +
+ Powered by Mifos Initiative +
+
+ ) +} diff --git a/src/modules/auth/Login.tsx b/src/modules/auth/Login.tsx index 89f091b..2608995 100644 --- a/src/modules/auth/Login.tsx +++ b/src/modules/auth/Login.tsx @@ -1,6 +1,6 @@ import React, { useState } from 'react' import { useNavigate } from 'react-router-dom' -import { User, Lock, Eye, EyeOff } from 'lucide-react' +import { User, Lock, Eye, EyeOff, Loader2 } from 'lucide-react' import { Input } from '@/components/ui/input' import { Button } from '@/components/ui/button' import { Label } from '@/components/ui/label' @@ -22,13 +22,40 @@ export default function Login() { const [tenant, setTenant] = useState('') const [rememberMe, setRememberMe] = useState(false) const [showPassword, setShowPassword] = useState(false) + const [loading, setLoading] = useState(false) + const [error, setError] = useState('') - function handleSubmit(e: React.FormEvent) { + async function handleSubmit(e: React.FormEvent) { e.preventDefault() - if (username === 'mifos' && password === 'password') { - navigate('/') - } else { - alert('Invalid credentials. Use mifos / password.') + setError('') + setLoading(true) + + try { + const response = await fetch( + `${import.meta.env.VITE_KEYCLOAK_URL}/realms/${import.meta.env.VITE_KEYCLOAK_REALM}/protocol/openid-connect/token`, + { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'password', + client_id: import.meta.env.VITE_KEYCLOAK_CLIENT_ID, + username, + password, + }), + }, + ) + const data = await response.json() + if (data.access_token) { + localStorage.setItem('kc_token', data.access_token) + localStorage.setItem('tenant', tenant) + navigate('/') + } else { + setError('Invalid username or password') + } + } catch { + setError('Unable to reach authentication server. Please try again.') + } finally { + setLoading(false) } } @@ -63,6 +90,7 @@ export default function Login() { onChange={(e) => setUsername(e.target.value)} className="pl-8" required + autoComplete="username" />
@@ -79,6 +107,7 @@ export default function Login() { onChange={(e) => setPassword(e.target.value)} className="pl-8 pr-9" required + autoComplete="current-password" /> diff --git a/src/modules/payment-hub/MainBatchesTab.tsx b/src/modules/payment-hub/MainBatchesTab.tsx index 52179a2..26dfc6f 100644 --- a/src/modules/payment-hub/MainBatchesTab.tsx +++ b/src/modules/payment-hub/MainBatchesTab.tsx @@ -18,7 +18,9 @@ import { SelectValue, } from '@/components/ui/select' import { Button } from '@/components/ui/button' -import { ChevronLeft, ChevronRight } from 'lucide-react' +import { ChevronLeft, ChevronRight, Download, FileText } from 'lucide-react' +import { exportCsv, csvDate } from '@/lib/exportCsv' +import { exportPdf } from '@/lib/exportPdf' const statuses: MainBatch['status'][] = [ 'Completed', @@ -40,7 +42,8 @@ export default function MainBatchesTab() { return (
- {/* Filters */} + {/* Filters + Export */} +
))}
+
+ + +
+
{/* Table */}
@@ -132,7 +161,7 @@ export default function MainBatchesTab() { setPage(1) }} > - + diff --git a/src/modules/payment-hub/SubBatchesTab.tsx b/src/modules/payment-hub/SubBatchesTab.tsx index b395033..8843594 100644 --- a/src/modules/payment-hub/SubBatchesTab.tsx +++ b/src/modules/payment-hub/SubBatchesTab.tsx @@ -18,7 +18,9 @@ import { SelectValue, } from '@/components/ui/select' import { Button } from '@/components/ui/button' -import { ChevronLeft, ChevronRight } from 'lucide-react' +import { ChevronLeft, ChevronRight, Download, FileText } from 'lucide-react' +import { exportCsv, csvDate } from '@/lib/exportCsv' +import { exportPdf } from '@/lib/exportPdf' const statuses: MainBatch['status'][] = [ 'Completed', @@ -40,7 +42,8 @@ export default function SubBatchesTab() { return (
- {/* Filters */} + {/* Filters + Export */} +
))}
+
+ + +
+
{/* Table */}
@@ -132,7 +161,7 @@ export default function SubBatchesTab() { setPage(1) }} > - + diff --git a/src/modules/payment-hub/TransfersTab.tsx b/src/modules/payment-hub/TransfersTab.tsx index a366de6..76942f4 100644 --- a/src/modules/payment-hub/TransfersTab.tsx +++ b/src/modules/payment-hub/TransfersTab.tsx @@ -18,7 +18,9 @@ import { SelectValue, } from '@/components/ui/select' import { Button } from '@/components/ui/button' -import { ChevronLeft, ChevronRight } from 'lucide-react' +import { ChevronLeft, ChevronRight, Download, FileText } from 'lucide-react' +import { exportCsv, csvDate } from '@/lib/exportCsv' +import { exportPdf } from '@/lib/exportPdf' const statuses: Transfer['status'][] = [ 'Completed', @@ -46,7 +48,8 @@ export default function TransfersTab() { return (
- {/* Filters */} + {/* Filters + Export */} +
+
+ + +
+
{/* Table */}
@@ -154,7 +183,7 @@ export default function TransfersTab() { setPage(1) }} > - + diff --git a/src/pages/AccountMapperSelfService.tsx b/src/pages/AccountMapperSelfService.tsx new file mode 100644 index 0000000..b0e4e7f --- /dev/null +++ b/src/pages/AccountMapperSelfService.tsx @@ -0,0 +1 @@ +export { default } from '@/modules/account-mapper/SelfServicePortal'