diff --git a/apps/customer-portal/webapp/package.json b/apps/customer-portal/webapp/package.json index e299f52554..b152b3f50c 100644 --- a/apps/customer-portal/webapp/package.json +++ b/apps/customer-portal/webapp/package.json @@ -26,6 +26,8 @@ "@wso2/oxygen-ui-charts-react": "^0.6.0", "@wso2/oxygen-ui-icons-react": "^0.6.0", "dompurify": "^3.3.1", + "jspdf": "^4.2.0", + "jspdf-autotable": "^5.0.7", "lexical": "^0.40.0", "prismjs": "^1.30.0", "react": "^19.2.0", @@ -56,4 +58,4 @@ "vite": "^7.2.4", "vitest": "^4.0.18" } -} +} \ No newline at end of file diff --git a/apps/customer-portal/webapp/pnpm-lock.yaml b/apps/customer-portal/webapp/pnpm-lock.yaml index 67ea554a97..45b77fafa2 100644 --- a/apps/customer-portal/webapp/pnpm-lock.yaml +++ b/apps/customer-portal/webapp/pnpm-lock.yaml @@ -53,6 +53,12 @@ importers: dompurify: specifier: ^3.3.1 version: 3.3.1 + jspdf: + specifier: ^4.2.0 + version: 4.2.0 + jspdf-autotable: + specifier: ^5.0.7 + version: 5.0.7(jspdf@4.2.0) lexical: specifier: ^0.40.0 version: 0.40.0 @@ -1283,6 +1289,9 @@ packages: '@types/node@24.10.13': resolution: {integrity: sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==} + '@types/pako@2.0.4': + resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==} + '@types/parse-json@4.0.2': resolution: {integrity: sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==} @@ -1292,6 +1301,9 @@ packages: '@types/prop-types@15.7.15': resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==} + '@types/raf@3.4.3': + resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==} + '@types/react-dom@19.1.5': resolution: {integrity: sha512-CMCjrWucUBZvohgZxkjd6S9h0nZxXjzus6yDfUb+xLxYM7VvjKNH1tQrE9GWLql1XoOP4/Ds3bwFqShHUYraGg==} peerDependencies: @@ -1509,6 +1521,10 @@ packages: balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + base64-arraybuffer@1.0.2: + resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==} + engines: {node: '>= 0.6.0'} + base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} @@ -1585,6 +1601,10 @@ packages: caniuse-lite@1.0.30001770: resolution: {integrity: sha512-x/2CLQ1jHENRbHg5PSId2sXq1CIO1CISvwWAj027ltMVG2UNgW+w9oH2+HzgEIRFembL8bUlXtfbBHR1fCg2xw==} + canvg@3.0.11: + resolution: {integrity: sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==} + engines: {node: '>=10.0.0'} + ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} @@ -1670,6 +1690,9 @@ packages: resolution: {integrity: sha512-r4ESw/IlusD17lgQi1O20Fa3qNnsckR126TdUuBgAu7GBYSIPvdNyONd3Zrxh0xCwA4+6w/TDArBPsMvhur+KQ==} engines: {node: '>= 0.10'} + css-line-break@2.1.0: + resolution: {integrity: sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==} + css-tree@3.1.0: resolution: {integrity: sha512-0eW44TGN5SQXU1mWSkKwFstI/22X2bG1nYzZTYMAWjylYURhse752YgbE4Cx46AC+bAvI+/dYTPRk1LqSUnu6w==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} @@ -1936,6 +1959,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-png@6.4.0: + resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==} + fast-sha256@1.3.0: resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==} @@ -1948,6 +1974,9 @@ packages: picomatch: optional: true + fflate@0.8.2: + resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==} + file-entry-cache@8.0.0: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} @@ -2074,6 +2103,10 @@ packages: html-url-attributes@3.0.1: resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==} + html2canvas@1.4.1: + resolution: {integrity: sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==} + engines: {node: '>=8.0.0'} + http-proxy-agent@7.0.2: resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} engines: {node: '>= 14'} @@ -2124,6 +2157,9 @@ packages: resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} engines: {node: '>=12'} + iobuffer@5.4.0: + resolution: {integrity: sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==} + is-alphabetical@2.0.1: resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==} @@ -2219,6 +2255,14 @@ packages: engines: {node: '>=6'} hasBin: true + jspdf-autotable@5.0.7: + resolution: {integrity: sha512-2wr7H6liNDBYNwt25hMQwXkEWFOEopgKIvR1Eukuw6Zmprm/ZcnmLTQEjW7Xx3FCbD3v7pflLcnMAv/h1jFDQw==} + peerDependencies: + jspdf: ^2 || ^3 || ^4 + + jspdf@4.2.0: + resolution: {integrity: sha512-hR/hnRevAXXlrjeqU5oahOE+Ln9ORJUB5brLHHqH67A+RBQZuFr5GkbI9XQI8OUFSEezKegsi45QRpc4bGj75Q==} + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} @@ -2429,6 +2473,9 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} + pako@2.1.0: + resolution: {integrity: sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -2469,6 +2516,9 @@ packages: resolution: {integrity: sha512-Q3CG/cYvCO1ye4QKkuH7EXxs3VC/rI1/trd+qX2+PolbaKG0H+bgcZzrTt96mMyRtejk+JMCiLUn3y29W8qmFQ==} engines: {node: '>= 0.10'} + performance-now@2.1.0: + resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -2519,6 +2569,9 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} + raf@3.4.1: + resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==} + randombytes@2.1.0: resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==} @@ -2624,6 +2677,9 @@ packages: redux@5.0.1: resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==} + regenerator-runtime@0.13.11: + resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==} + remark-parse@11.0.0: resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==} @@ -2646,6 +2702,10 @@ packages: engines: {node: '>= 0.4'} hasBin: true + rgbcolor@1.0.1: + resolution: {integrity: sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==} + engines: {node: '>= 0.8.15'} + ripemd160@2.0.3: resolution: {integrity: sha512-5Di9UC0+8h1L6ZD2d7awM7E/T4uA1fJRlx6zk/NvdCCVEoAnFqvHmCuNeIKoCeIixBX/q8uM+6ycDvF8woqosA==} engines: {node: '>= 0.8'} @@ -2717,6 +2777,10 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + stackblur-canvas@2.7.0: + resolution: {integrity: sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==} + engines: {node: '>=0.1.14'} + std-env@3.10.0: resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} @@ -2757,12 +2821,19 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} + svg-pathdata@6.0.3: + resolution: {integrity: sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==} + engines: {node: '>=12.0.0'} + symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} tabbable@6.4.0: resolution: {integrity: sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg==} + text-segmentation@1.0.3: + resolution: {integrity: sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==} + tiny-invariant@1.3.3: resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} @@ -2873,6 +2944,9 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + utrie@1.0.2: + resolution: {integrity: sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==} + vfile-message@4.0.3: resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==} @@ -4174,12 +4248,17 @@ snapshots: dependencies: undici-types: 7.16.0 + '@types/pako@2.0.4': {} + '@types/parse-json@4.0.2': {} '@types/prismjs@1.26.6': {} '@types/prop-types@15.7.15': {} + '@types/raf@3.4.3': + optional: true + '@types/react-dom@19.1.5(@types/react@19.2.14)': dependencies: '@types/react': 19.2.14 @@ -4458,6 +4537,9 @@ snapshots: balanced-match@1.0.2: {} + base64-arraybuffer@1.0.2: + optional: true + base64-js@1.5.1: {} base64url@3.0.1: {} @@ -4559,6 +4641,18 @@ snapshots: caniuse-lite@1.0.30001770: {} + canvg@3.0.11: + dependencies: + '@babel/runtime': 7.28.6 + '@types/raf': 3.4.3 + core-js: 3.42.0 + raf: 3.4.1 + regenerator-runtime: 0.13.11 + rgbcolor: 1.0.1 + stackblur-canvas: 2.7.0 + svg-pathdata: 6.0.3 + optional: true + ccount@2.0.1: {} chai@6.2.2: {} @@ -4659,6 +4753,11 @@ snapshots: randombytes: 2.1.0 randomfill: 1.0.4 + css-line-break@2.1.0: + dependencies: + utrie: 1.0.2 + optional: true + css-tree@3.1.0: dependencies: mdn-data: 2.12.2 @@ -4989,12 +5088,20 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-png@6.4.0: + dependencies: + '@types/pako': 2.0.4 + iobuffer: 5.4.0 + pako: 2.1.0 + fast-sha256@1.3.0: {} fdir@6.5.0(picomatch@4.0.3): optionalDependencies: picomatch: 4.0.3 + fflate@0.8.2: {} + file-entry-cache@8.0.0: dependencies: flat-cache: 4.0.1 @@ -5143,6 +5250,12 @@ snapshots: html-url-attributes@3.0.1: {} + html2canvas@1.4.1: + dependencies: + css-line-break: 2.1.0 + text-segmentation: 1.0.3 + optional: true + http-proxy-agent@7.0.2: dependencies: agent-base: 7.1.4 @@ -5184,6 +5297,8 @@ snapshots: internmap@2.0.3: {} + iobuffer@5.4.0: {} + is-alphabetical@2.0.1: {} is-alphanumerical@2.0.1: @@ -5273,6 +5388,21 @@ snapshots: json5@2.2.3: {} + jspdf-autotable@5.0.7(jspdf@4.2.0): + dependencies: + jspdf: 4.2.0 + + jspdf@4.2.0: + dependencies: + '@babel/runtime': 7.28.6 + fast-png: 6.4.0 + fflate: 0.8.2 + optionalDependencies: + canvg: 3.0.11 + core-js: 3.42.0 + dompurify: 3.3.1 + html2canvas: 1.4.1 + keyv@4.5.4: dependencies: json-buffer: 3.0.1 @@ -5604,6 +5734,8 @@ snapshots: dependencies: p-limit: 3.1.0 + pako@2.1.0: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 @@ -5656,6 +5788,9 @@ snapshots: sha.js: 2.4.12 to-buffer: 1.2.2 + performance-now@2.1.0: + optional: true + picocolors@1.1.1: {} picomatch@4.0.3: {} @@ -5703,6 +5838,11 @@ snapshots: punycode@2.3.1: {} + raf@3.4.1: + dependencies: + performance-now: 2.1.0 + optional: true + randombytes@2.1.0: dependencies: safe-buffer: 5.2.1 @@ -5832,6 +5972,9 @@ snapshots: redux@5.0.1: {} + regenerator-runtime@0.13.11: + optional: true + remark-parse@11.0.0: dependencies: '@types/mdast': 4.0.4 @@ -5861,6 +6004,9 @@ snapshots: path-parse: 1.0.7 supports-preserve-symlinks-flag: 1.0.0 + rgbcolor@1.0.1: + optional: true + ripemd160@2.0.3: dependencies: hash-base: 3.1.2 @@ -5946,6 +6092,9 @@ snapshots: stackback@0.0.2: {} + stackblur-canvas@2.7.0: + optional: true + std-env@3.10.0: {} stream-browserify@3.0.0: @@ -5988,10 +6137,18 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} + svg-pathdata@6.0.3: + optional: true + symbol-tree@3.2.4: {} tabbable@6.4.0: {} + text-segmentation@1.0.3: + dependencies: + utrie: 1.0.2 + optional: true + tiny-invariant@1.3.3: {} tinybench@2.9.0: {} @@ -6109,6 +6266,11 @@ snapshots: util-deprecate@1.0.2: {} + utrie@1.0.2: + dependencies: + base64-arraybuffer: 1.0.2 + optional: true + vfile-message@4.0.3: dependencies: '@types/unist': 3.0.3 diff --git a/apps/customer-portal/webapp/src/App.tsx b/apps/customer-portal/webapp/src/App.tsx index fb36fa85fd..14f55aa141 100644 --- a/apps/customer-portal/webapp/src/App.tsx +++ b/apps/customer-portal/webapp/src/App.tsx @@ -23,6 +23,7 @@ import DashboardPage from "@pages/DashboardPage"; import SupportPage from "@pages/SupportPage"; import UpdatesPage from "@pages/UpdatesPage"; import PendingUpdatesPage from "@pages/PendingUpdatesPage"; +import UpdateLevelDetailsPage from "@pages/UpdateLevelDetailsPage"; import AllCasesPage from "@pages/AllCasesPage"; import CaseDetailsPage from "@pages/CaseDetailsPage"; import NoveraChatPage from "@pages/NoveraChatPage"; @@ -96,10 +97,13 @@ export default function App(): JSX.Element { {/* Updates */} } /> - } - /> + + } /> + } + /> + {/* SecurityCenter */} diff --git a/apps/customer-portal/webapp/src/api/usePostCreateDeployment.ts b/apps/customer-portal/webapp/src/api/usePostCreateDeployment.ts index 20fa71287f..52d718f0c5 100644 --- a/apps/customer-portal/webapp/src/api/usePostCreateDeployment.ts +++ b/apps/customer-portal/webapp/src/api/usePostCreateDeployment.ts @@ -67,6 +67,12 @@ export function usePostCreateDeployment( `[usePostCreateDeployment] Response status: ${response.status}`, ); + if (response.status === 409) { + throw new Error( + `Deployment name "${body.name}" is already taken. Please choose a different name.`, + ); + } + if (!response.ok) { const text = await response.text(); throw new Error( @@ -83,10 +89,10 @@ export function usePostCreateDeployment( } }, onSuccess: () => { - queryClient.invalidateQueries({ + void queryClient.refetchQueries({ queryKey: ["project-deployments", projectId], }); - queryClient.invalidateQueries({ + void queryClient.refetchQueries({ queryKey: [ApiQueryKeys.DEPLOYMENTS, projectId], }); }, diff --git a/apps/customer-portal/webapp/src/api/usePostUpdateLevelsSearch.ts b/apps/customer-portal/webapp/src/api/usePostUpdateLevelsSearch.ts new file mode 100644 index 0000000000..d76f3714b4 --- /dev/null +++ b/apps/customer-portal/webapp/src/api/usePostUpdateLevelsSearch.ts @@ -0,0 +1,81 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { useQuery, type UseQueryResult } from "@tanstack/react-query"; +import { useAsgardeo } from "@asgardeo/react"; +import { useLogger } from "@hooks/useLogger"; +import { useAuthApiClient } from "@context/AuthApiContext"; +import { ApiQueryKeys } from "@constants/apiConstants"; +import type { UpdateLevelsSearchRequest } from "@models/requests"; +import type { UpdateLevelsSearchResponse } from "@models/responses"; + +/** + * Searches for update level descriptions using POST /updates/levels/search. + * The startingUpdateLevel maps to the product's current level; + * endingUpdateLevel maps to the latest recommended level. + * + * @param {UpdateLevelsSearchRequest | null} params - Search parameters or null to disable. + * @returns {UseQueryResult} The query result. + */ +export function usePostUpdateLevelsSearch( + params: UpdateLevelsSearchRequest | null, +): UseQueryResult { + const logger = useLogger(); + const { isSignedIn, isLoading: isAuthLoading } = useAsgardeo(); + const fetchFn = useAuthApiClient(); + + return useQuery({ + queryKey: [ + ApiQueryKeys.UPDATE_LEVELS_SEARCH, + params?.productName, + params?.productVersion, + params?.startingUpdateLevel, + params?.endingUpdateLevel, + ], + queryFn: async (): Promise => { + logger.debug("[usePostUpdateLevelsSearch] Request params:", params); + + const baseUrl = window.config?.CUSTOMER_PORTAL_BACKEND_BASE_URL; + if (!baseUrl) { + throw new Error("CUSTOMER_PORTAL_BACKEND_BASE_URL is not configured"); + } + + const requestUrl = `${baseUrl}/updates/levels/search`; + + const response = await fetchFn(requestUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(params), + }); + + logger.debug( + `[usePostUpdateLevelsSearch] Response status: ${response.status}`, + ); + + if (!response.ok) { + throw new Error( + `Error fetching update levels: ${response.status} ${response.statusText}`, + ); + } + + const data: UpdateLevelsSearchResponse = await response.json(); + logger.debug("[usePostUpdateLevelsSearch] Data received:", data); + return data; + }, + enabled: !!params && isSignedIn && !isAuthLoading, + staleTime: 5 * 60 * 1000, + }); +} diff --git a/apps/customer-portal/webapp/src/components/updates/all-updates/AllUpdatesTab.tsx b/apps/customer-portal/webapp/src/components/updates/all-updates/AllUpdatesTab.tsx new file mode 100644 index 0000000000..94eb45db39 --- /dev/null +++ b/apps/customer-portal/webapp/src/components/updates/all-updates/AllUpdatesTab.tsx @@ -0,0 +1,408 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { + Box, + Button, + Card, + CardContent, + FormControl, + Grid, + InputLabel, + MenuItem, + Paper, + Select, + Stack, + Typography, +} from "@wso2/oxygen-ui"; +import { FileText } from "@wso2/oxygen-ui-icons-react"; +import { useCallback, useMemo, useState, type JSX } from "react"; +import { useNavigate, useParams } from "react-router"; +import type { SelectChangeEvent } from "@wso2/oxygen-ui"; +import { useGetRecommendedUpdateLevels } from "@api/useGetRecommendedUpdateLevels"; +import { usePostUpdateLevelsSearch } from "@api/usePostUpdateLevelsSearch"; +import { PendingUpdatesList } from "@components/updates/pending-updates/PendingUpdatesList"; +import PendingUpdatesListSkeleton from "@components/updates/pending-updates/PendingUpdatesListSkeleton"; +import EmptyState from "@components/common/empty-state/EmptyState"; +import ErrorStateIcon from "@components/common/error-state/ErrorStateIcon"; +import UpdateLevelsReportModal from "@components/updates/all-updates/UpdateLevelsReportModal"; +import type { RecommendedUpdateLevelItem } from "@models/responses"; +import { getUpdateLevelsReportData } from "@utils/updateLevelsReportPdf"; + +export interface AllUpdatesTabFilterState { + productName: string; + productVersion: string; + startLevel: string; + endLevel: string; +} + +const INITIAL_FILTER: AllUpdatesTabFilterState = { + productName: "", + productVersion: "", + startLevel: "", + endLevel: "", +}; + +function isValidFilter( + f: AllUpdatesTabFilterState, +): { valid: true; start: number; end: number } | { valid: false } { + const start = Number(f.startLevel); + const end = Number(f.endLevel); + if ( + !f.productName || + !f.productVersion || + f.startLevel === "" || + f.endLevel === "" || + !Number.isFinite(start) || + !Number.isFinite(end) || + start < 0 || + end < 0 || + start > end + ) { + return { valid: false }; + } + return { valid: true, start, end }; +} + +/** + * Derives unique product names from recommended update level data. + * + * @param {RecommendedUpdateLevelItem[] | undefined} data - Raw recommended levels. + * @returns {string[]} Sorted unique product names. + */ +function getProductNames(data: RecommendedUpdateLevelItem[] | undefined): string[] { + if (!data?.length) return []; + const names = [...new Set(data.map((d) => d.productName))]; + return names.sort(); +} + +/** + * Derives product versions for a selected product. + * + * @param {RecommendedUpdateLevelItem[] | undefined} data - Raw recommended levels. + * @param {string} productName - Selected product. + * @returns {RecommendedUpdateLevelItem[]} Matching items. + */ +function getVersionsForProduct( + data: RecommendedUpdateLevelItem[] | undefined, + productName: string, +): RecommendedUpdateLevelItem[] { + if (!data?.length || !productName) return []; + return data.filter((d) => d.productName === productName); +} + +/** + * AllUpdatesTab displays a filter section and search results for update levels. + * Uses GET /updates/recommended-update-levels for dropdown options and + * POST /updates/levels/search for results. + * + * @returns {JSX.Element} The rendered All Updates tab content. + */ +export default function AllUpdatesTab(): JSX.Element { + const navigate = useNavigate(); + const { projectId } = useParams<{ projectId: string }>(); + + const [filter, setFilter] = useState(INITIAL_FILTER); + const [reportModalOpen, setReportModalOpen] = useState(false); + const [searchParams, setSearchParams] = useState<{ + productName: string; + productVersion: string; + startingUpdateLevel: number; + endingUpdateLevel: number; + } | null>(null); + + const { data: recommendedData, isLoading: isRecommendedLoading, isError: isRecommendedError } = useGetRecommendedUpdateLevels(); + + const { data: searchData, isLoading: isSearchLoading, isError: isSearchError } = usePostUpdateLevelsSearch(searchParams); + + const productNames = useMemo(() => getProductNames(recommendedData), [recommendedData]); + + const versionItems = useMemo( + () => getVersionsForProduct(recommendedData, filter.productName), + [recommendedData, filter.productName], + ); + + const selectedItem = useMemo( + () => + versionItems.find( + (v) => v.productName === filter.productName && v.productBaseVersion === filter.productVersion, + ), + [versionItems, filter.productName, filter.productVersion], + ); + + const startLevelOptions = useMemo(() => { + if (!selectedItem) return []; + const max = selectedItem.recommendedUpdateLevel; + const min = Math.min(selectedItem.startingUpdateLevel, max); + const opts: number[] = []; + for (let i = min; i <= max; i++) opts.push(i); + return opts; + }, [selectedItem]); + + const endLevelOptions = useMemo(() => { + if (!selectedItem || !filter.startLevel) return []; + const start = Number(filter.startLevel); + const max = selectedItem.recommendedUpdateLevel; + const opts: number[] = []; + for (let i = start; i <= max; i++) opts.push(i); + return opts; + }, [selectedItem, filter.startLevel]); + + const handleFilterChange = useCallback( + (field: keyof AllUpdatesTabFilterState) => (e: SelectChangeEvent) => { + const value = e.target.value; + setFilter((prev) => { + const next = { ...prev, [field]: value }; + if (field === "productName") { + next.productVersion = ""; + next.startLevel = ""; + next.endLevel = ""; + } else if (field === "productVersion") { + next.startLevel = ""; + next.endLevel = ""; + } else if (field === "startLevel") { + next.endLevel = ""; + } + return next; + }); + }, + [], + ); + + const handleSearch = useCallback(() => { + const result = isValidFilter(filter); + if (!result.valid) return; + setSearchParams({ + productName: filter.productName, + productVersion: filter.productVersion, + startingUpdateLevel: result.start, + endingUpdateLevel: result.end, + }); + }, [filter]); + + const handleView = useCallback( + (levelKey: string) => { + if (!searchParams || !projectId) return; + const params = new URLSearchParams({ + productName: searchParams.productName, + productBaseVersion: searchParams.productVersion, + startingUpdateLevel: String(searchParams.startingUpdateLevel), + endingUpdateLevel: String(searchParams.endingUpdateLevel), + }); + navigate(`/${projectId}/updates/pending/level/${levelKey}?${params}`); + }, + [navigate, projectId, searchParams], + ); + + const reportData = useMemo(() => { + if (!searchData || !searchParams || Object.keys(searchData).length === 0) return null; + try { + return getUpdateLevelsReportData({ + productName: searchParams.productName, + productVersion: searchParams.productVersion, + startLevel: searchParams.startingUpdateLevel, + endLevel: searchParams.endingUpdateLevel, + data: searchData, + }); + } catch { + return null; + } + }, [searchData, searchParams]); + + const handleViewReport = useCallback(() => { + if (!reportData) return; + setReportModalOpen(true); + }, [reportData]); + + const canSearch = isValidFilter(filter).valid; + + const canViewReport = !!reportData; + + if (isRecommendedError) { + return ( + + + + Could not load filter options. Please try again later. + + + ); + } + + return ( + + + + + Search Update Levels + + + + + Product Name * + + + + + + Product Version * + + + + + + Starting Update Level * + + + + + + Ending Update Level * + + + + + + + + + + + + {!searchParams ? ( + + + Select product, version, and update level range, then click Search to view updates. + + + ) : isSearchLoading ? ( + + ) : isSearchError ? ( + + + + Failed to load update levels. Please try again. + + + ) : searchData && Object.keys(searchData).length === 0 ? ( + + ) : ( + + )} + + setReportModalOpen(false)} + /> + + ); +} diff --git a/apps/customer-portal/webapp/src/components/updates/all-updates/UpdateLevelsReportModal.tsx b/apps/customer-portal/webapp/src/components/updates/all-updates/UpdateLevelsReportModal.tsx new file mode 100644 index 0000000000..59bca6965b --- /dev/null +++ b/apps/customer-portal/webapp/src/components/updates/all-updates/UpdateLevelsReportModal.tsx @@ -0,0 +1,184 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { + Box, + Button, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + IconButton, + Paper, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@wso2/oxygen-ui"; +import { Printer, X } from "@wso2/oxygen-ui-icons-react"; +import { useCallback, type JSX } from "react"; +import { generateUpdateLevelsReportPdf, type UpdateLevelsReportData } from "@utils/updateLevelsReportPdf"; + +export interface UpdateLevelsReportModalProps { + open: boolean; + reportData: UpdateLevelsReportData | null; + onClose: () => void; +} + +/** + * Modal that displays the Update Levels Report. + * User can click "Download PDF" to generate and download the report via jspdf-autotable. + * + * @param {UpdateLevelsReportModalProps} props - open, reportData, onClose. + * @returns {JSX.Element | null} The report modal or null when reportData is missing. + */ +export default function UpdateLevelsReportModal({ + open, + reportData, + onClose, +}: UpdateLevelsReportModalProps): JSX.Element | null { + const handleDownloadPdf = useCallback(() => { + if (!reportData) return; + generateUpdateLevelsReportPdf(reportData); + }, [reportData]); + + if (!reportData) { + return null; + } + + return ( + + + Update Levels Report + + + + + + + + Generated on: {reportData.generatedStr} + + + + Search Criteria + + + + Product: {reportData.productName} + + + Version: {reportData.productVersion} + + + Update Level Range: {reportData.startLevel} to {reportData.endLevel} + + + View Mode: All Updates + + + Total Updates: {reportData.totalUpdates} + + + Update Levels: {reportData.levelCount} levels ({reportData.levelsRange}) + + + + + Update Levels Summary + + + + Security Updates: {reportData.securityCount} + + + Regular Updates: {reportData.regularCount} + + + Mixed Updates: {reportData.mixedCount} + + + Applied Updates: N/A + + + Pending Updates: {reportData.levelCount} + + + + + Update Levels Details + + + + + + Level + Type + Updates + Release Date + Applied + + + + {reportData.tableRows.map((row) => ( + + {row.levelKey} + {row.typeLabel} + {row.updatesCount} + {row.releaseDate} + {row.applied} + + ))} + +
+
+ + + {reportData.productName} {reportData.productVersion} - Update Levels Report + +
+
+ + + + +
+ ); +} diff --git a/apps/customer-portal/webapp/src/components/updates/all-updates/__tests__/AllUpdatesTab.test.tsx b/apps/customer-portal/webapp/src/components/updates/all-updates/__tests__/AllUpdatesTab.test.tsx new file mode 100644 index 0000000000..741b3b9af0 --- /dev/null +++ b/apps/customer-portal/webapp/src/components/updates/all-updates/__tests__/AllUpdatesTab.test.tsx @@ -0,0 +1,99 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { render, screen } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { MemoryRouter } from "react-router"; +import AllUpdatesTab from "@components/updates/all-updates/AllUpdatesTab"; + +vi.mock("@api/useGetRecommendedUpdateLevels", () => ({ + useGetRecommendedUpdateLevels: () => ({ + data: [ + { + productName: "WSO2 API Manager", + productBaseVersion: "4.4.0", + channel: "full", + startingUpdateLevel: 2, + endingUpdateLevel: 19, + recommendedUpdateLevel: 19, + installedUpdatesCount: 3, + installedSecurityUpdatesCount: 2, + availableUpdatesCount: 15, + availableSecurityUpdatesCount: 10, + timestamp: 0, + }, + ], + isLoading: false, + isError: false, + }), +})); + +vi.mock("@api/usePostUpdateLevelsSearch", () => ({ + usePostUpdateLevelsSearch: () => ({ + data: null, + isLoading: false, + isError: false, + }), +})); + +vi.mock("react-router", async (importOriginal) => { + const orig = await importOriginal(); + return { + ...orig, + useNavigate: () => vi.fn(), + useParams: () => ({ projectId: "test-project-id" }), + }; +}); + +describe("AllUpdatesTab", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("renders filter section with dropdown labels", () => { + render( + + + , + ); + expect(screen.getByText("Search Update Levels")).toBeDefined(); + expect(screen.getByLabelText(/Product Name/)).toBeDefined(); + expect(screen.getByLabelText(/Product Version/)).toBeDefined(); + expect(screen.getByLabelText(/Starting Update Level/)).toBeDefined(); + expect(screen.getByLabelText(/Ending Update Level/)).toBeDefined(); + }); + + it("renders Search and View Report buttons", () => { + render( + + + , + ); + expect(screen.getByRole("button", { name: /Search/i })).toBeDefined(); + expect(screen.getByRole("button", { name: /View Report/i })).toBeDefined(); + }); + + it("shows placeholder text when no search has been run", () => { + render( + + + , + ); + expect( + screen.getByText(/Select product, version, and update level range/), + ).toBeDefined(); + }); +}); diff --git a/apps/customer-portal/webapp/src/components/updates/all-updates/__tests__/UpdateLevelsReportModal.test.tsx b/apps/customer-portal/webapp/src/components/updates/all-updates/__tests__/UpdateLevelsReportModal.test.tsx new file mode 100644 index 0000000000..f3433dc5d2 --- /dev/null +++ b/apps/customer-portal/webapp/src/components/updates/all-updates/__tests__/UpdateLevelsReportModal.test.tsx @@ -0,0 +1,72 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { render, screen } from "@testing-library/react"; +import { describe, it, expect, vi } from "vitest"; +import UpdateLevelsReportModal from "@components/updates/all-updates/UpdateLevelsReportModal"; +import type { UpdateLevelsReportData } from "@utils/updateLevelsReportPdf"; + +const mockReportData: UpdateLevelsReportData = { + generatedStr: "February 23, 2026 at 8:00 PM", + productName: "WSO2 API Manager", + productVersion: "4.4.0", + startLevel: 2, + endLevel: 19, + securityCount: 14, + regularCount: 4, + mixedCount: 0, + totalUpdates: 39, + levelCount: 18, + levelsRange: "2 - 19", + tableRows: [ + { levelKey: "2", typeLabel: "Regular", updatesCount: 2, releaseDate: "Jan 22, 2024", applied: "Yes" }, + { levelKey: "3", typeLabel: "Security", updatesCount: 1, releaseDate: "Feb 5, 2024", applied: "Yes" }, + ], +}; + +describe("UpdateLevelsReportModal", () => { + it("renders report content when open with reportData", () => { + render( + , + ); + + expect(screen.getByText("Update Levels Report")).toBeDefined(); + expect(screen.getByText(/Generated on:/)).toBeDefined(); + expect(screen.getByText(/Update Level Range: 2 to 19/)).toBeDefined(); + expect(screen.getByRole("button", { name: /Download PDF/i })).toBeDefined(); + expect(screen.getAllByRole("button", { name: /Close/i }).length).toBeGreaterThanOrEqual(1); + expect(screen.getByText("Search Criteria")).toBeDefined(); + expect(screen.getByText("Update Levels Details")).toBeDefined(); + expect(screen.getByText("Level")).toBeDefined(); + expect(screen.getByText("Type")).toBeDefined(); + }); + + it("renders nothing visible when reportData is null", () => { + render( + , + ); + + expect(screen.queryByText("Update Levels Report")).toBeNull(); + }); +}); diff --git a/apps/customer-portal/webapp/src/components/updates/pending-updates/PendingUpdatesList.tsx b/apps/customer-portal/webapp/src/components/updates/pending-updates/PendingUpdatesList.tsx index b00c6f0380..6c1534f643 100644 --- a/apps/customer-portal/webapp/src/components/updates/pending-updates/PendingUpdatesList.tsx +++ b/apps/customer-portal/webapp/src/components/updates/pending-updates/PendingUpdatesList.tsx @@ -15,7 +15,10 @@ // under the License. import { + alpha, Box, + Button, + Chip, Paper, Table, TableBody, @@ -24,95 +27,193 @@ import { TableHead, TableRow, Typography, + useTheme, } from "@wso2/oxygen-ui"; import type { JSX } from "react"; -import type { RecommendedUpdateLevelItem } from "@models/responses"; -import type { PendingUpdateLevelRow } from "@utils/updates"; +import type { UpdateLevelsSearchResponse } from "@models/responses"; +import { getUpdateTypeChipColor } from "@utils/updates"; +import EmptyState from "@components/common/empty-state/EmptyState"; +import ErrorStateIcon from "@components/common/error-state/ErrorStateIcon"; export interface PendingUpdatesListProps { - pendingRows: PendingUpdateLevelRow[]; - recommendedItem: RecommendedUpdateLevelItem | undefined; + data: UpdateLevelsSearchResponse | null; + isError: boolean; + onView: (levelKey: string) => void; } /** - * Component to display pending update levels in a table. + * Displays pending update levels as a simple table. + * Each row shows the update level number, update type chip, and a View button. * - * @param {PendingUpdatesListProps} props - Pending rows and recommended item for summary. + * @param {PendingUpdatesListProps} props - Response data, error state, and view callback. * @returns {JSX.Element} The rendered pending updates table. */ export function PendingUpdatesList({ - pendingRows, - recommendedItem, + data, + isError, + onView, }: PendingUpdatesListProps): JSX.Element { - const securityCount = pendingRows.filter((r) => r.updateType === "security").length; - const regularCount = pendingRows.filter((r) => r.updateType === "regular").length; + const theme = useTheme(); - if (pendingRows.length === 0) { + if (isError) { return ( - - - No pending updates found for this product and version. + + + + Failed to load pending updates. ); } + const entries = data ? Object.entries(data).sort(([a], [b]) => Number(a) - Number(b)) : []; + + const securityCount = entries.filter(([, e]) => e.updateType === "security").length; + const regularCount = entries.filter(([, e]) => e.updateType === "regular").length; + const mixedCount = entries.filter(([, e]) => e.updateType === "mixed").length; + + if (entries.length === 0) { + return ( + + ); + } + return ( - {recommendedItem && ( - - There are {pendingRows.length} updates with{" "} - {securityCount} security updates and{" "} - {regularCount} regular updates. - - )} + + There are {entries.length} updates with{" "} + {securityCount} security, {regularCount} regular + {mixedCount > 0 && ( + <> + , and {mixedCount} mixed + + )}{" "} + updates. + - - - - - - Update Level - - - Update Type - - - Details - - - - - {pendingRows.map((row) => ( - - {row.updateLevel} - - - -- + +
+ + + + Update Level + + + Update Type + + + Details + + + + + {entries.map(([levelKey, entry]) => { + const chipColor = getUpdateTypeChipColor(entry.updateType); + return ( + + + + {levelKey} - + + + + + + - ))} - -
+ ); + })} + +
); diff --git a/apps/customer-portal/webapp/src/components/updates/pending-updates/__tests__/PendingUpdatesList.test.tsx b/apps/customer-portal/webapp/src/components/updates/pending-updates/__tests__/PendingUpdatesList.test.tsx index b688b565fd..96a0f3c019 100644 --- a/apps/customer-portal/webapp/src/components/updates/pending-updates/__tests__/PendingUpdatesList.test.tsx +++ b/apps/customer-portal/webapp/src/components/updates/pending-updates/__tests__/PendingUpdatesList.test.tsx @@ -14,75 +14,123 @@ // specific language governing permissions and limitations // under the License. -import { render, screen } from "@testing-library/react"; -import { describe, it, expect } from "vitest"; +import { render, screen, fireEvent } from "@testing-library/react"; +import { describe, it, expect, vi } from "vitest"; import { PendingUpdatesList } from "@components/updates/pending-updates/PendingUpdatesList"; -import type { RecommendedUpdateLevelItem } from "@models/responses"; +import type { UpdateLevelsSearchResponse } from "@models/responses"; -const mockRecommended: RecommendedUpdateLevelItem = { - productName: "wso2am", - productBaseVersion: "4.2.0", - channel: "full", - startingUpdateLevel: 0, - endingUpdateLevel: 11, - installedUpdatesCount: 46, - installedSecurityUpdatesCount: 3, - timestamp: 0, - recommendedUpdateLevel: 22, - availableUpdatesCount: 44, - availableSecurityUpdatesCount: 9, +const mockData: UpdateLevelsSearchResponse = { + "7": { + updateType: "regular", + updateDescriptionLevels: [ + { + updateLevel: 7, + productName: "wso2am", + productVersion: "4.2.0", + channel: "full", + updateType: "regular", + updateNumber: 912, + description: "Fix for dashboard issue.", + instructions: "N/A", + bugFixes: "[]", + filesAdded: "[]", + filesModified: "[]", + filesRemoved: "[]", + bundlesInfoChanges: null, + dependantReleases: null, + timestamp: 1618554310000, + securityAdvisories: [], + }, + ], + }, + "8": { + updateType: "security", + updateDescriptionLevels: [ + { + updateLevel: 8, + productName: "wso2am", + productVersion: "4.2.0", + channel: "full", + updateType: "security", + updateNumber: 973, + description: "Security patch for HSTS headers.", + instructions: "N/A", + bugFixes: "[]", + filesAdded: "[]", + filesModified: "[]", + filesRemoved: "[]", + bundlesInfoChanges: null, + dependantReleases: null, + timestamp: 1619148655000, + securityAdvisories: [ + { + id: "WSO2-2021-1402", + overview: "HSTS header enhancement.", + severity: "Low", + description: "Missing HSTS header.", + impact: "Info disclosure.", + solution: "Apply patch.", + notes: "Tested.", + credits: "-", + }, + ], + }, + ], + }, }; -const mockPendingRows = [ - { updateLevel: 12, updateType: "regular" as const }, - { updateLevel: 13, updateType: "security" as const }, - { updateLevel: 14, updateType: "security" as const }, -]; - describe("PendingUpdatesList", () => { - it("renders empty state when pendingRows is empty", () => { - render( - , - ); + it("renders empty state when data is null", () => { + render(); + expect( + screen.getByText("No pending updates found for this product and version."), + ).toBeDefined(); + }); + + it("renders empty state when data is empty object", () => { + render(); expect( screen.getByText("No pending updates found for this product and version."), ).toBeDefined(); }); - it("renders summary when recommendedItem is provided", () => { - render( - , - ); - expect(screen.getByText(/There are .* 3 .* updates/)).toBeDefined(); + it("renders error state when isError is true", () => { + render(); + expect(document.querySelector("svg")).toBeTruthy(); + }); + + it("renders summary text with correct counts", () => { + render(); + expect(screen.getByText(/updates with/)).toBeDefined(); + expect(screen.getByText(/security/)).toBeDefined(); + expect(screen.getByText(/regular/)).toBeDefined(); + expect(screen.getByText(/updates\./)).toBeDefined(); }); - it("renders table with Update Level, Update Type, Details columns", () => { - render( - , - ); + it("renders table header columns", () => { + render(); expect(screen.getByText("Update Level")).toBeDefined(); expect(screen.getByText("Update Type")).toBeDefined(); expect(screen.getByText("Details")).toBeDefined(); }); - it("renders each pending row with level and type badge", () => { - render( - , - ); - expect(screen.getByText("12")).toBeDefined(); - expect(screen.getByText("13")).toBeDefined(); - expect(screen.getByText("14")).toBeDefined(); - expect(screen.getAllByText("Security").length).toBeGreaterThan(0); - expect(screen.getAllByText("Regular").length).toBeGreaterThan(0); - expect(screen.getAllByText("View").length).toBe(3); + it("renders each update level row with label and chip", () => { + render(); + expect(screen.getByText("7")).toBeDefined(); + expect(screen.getByText("8")).toBeDefined(); + expect(screen.getByText("Regular")).toBeDefined(); + expect(screen.getByText("Security")).toBeDefined(); + expect(screen.getAllByText("View").length).toBe(2); + }); + + it("invokes onView with the correct levelKey when View button is clicked", () => { + const onView = vi.fn(); + render(); + const viewButtons = screen.getAllByText("View"); + expect(viewButtons).toHaveLength(2); + fireEvent.click(viewButtons[0]); + expect(onView).toHaveBeenCalledWith("7"); + fireEvent.click(viewButtons[1]); + expect(onView).toHaveBeenCalledWith("8"); }); }); diff --git a/apps/customer-portal/webapp/src/components/updates/update-cards/UpdateProductGrid.tsx b/apps/customer-portal/webapp/src/components/updates/update-cards/UpdateProductGrid.tsx index 891c45498d..21a9f7f79c 100644 --- a/apps/customer-portal/webapp/src/components/updates/update-cards/UpdateProductGrid.tsx +++ b/apps/customer-portal/webapp/src/components/updates/update-cards/UpdateProductGrid.tsx @@ -17,6 +17,8 @@ import { Box, Grid, Typography } from "@wso2/oxygen-ui"; import { useNavigate } from "react-router"; import type { JSX } from "react"; +import ErrorStateIcon from "@components/common/error-state/ErrorStateIcon"; +import EmptyState from "@components/common/empty-state/EmptyState"; import type { RecommendedUpdateLevelItem } from "@models/responses"; import { UpdateProductCard } from "@update-cards/UpdateProductCard"; import { UpdateProductCardSkeleton } from "@update-cards/UpdateProductCardSkeleton"; @@ -44,10 +46,17 @@ export function UpdateProductGrid({ if (isError) { return ( - - - Failed to load product updates. - + + ); } @@ -69,6 +78,8 @@ export function UpdateProductGrid({
{isLoading || !data ? ( renderSkeletons() + ) : data.length === 0 ? ( + ) : ( {data.map((item) => ( @@ -84,6 +95,8 @@ export function UpdateProductGrid({ const params = new URLSearchParams({ productName: item.productName, productBaseVersion: item.productBaseVersion, + startingUpdateLevel: String(item.startingUpdateLevel), + endingUpdateLevel: String(item.recommendedUpdateLevel), }); navigate(`/${projectId}/updates/pending?${params}`); } diff --git a/apps/customer-portal/webapp/src/constants/apiConstants.ts b/apps/customer-portal/webapp/src/constants/apiConstants.ts index a28cbea764..2ef82a62df 100644 --- a/apps/customer-portal/webapp/src/constants/apiConstants.ts +++ b/apps/customer-portal/webapp/src/constants/apiConstants.ts @@ -44,4 +44,5 @@ export const ApiQueryKeys = { TIME_TRACKING_DETAILS: "time-tracking-details", TIME_CARDS_SEARCH: "time-cards-search", PROJECT_DEPLOYMENT_DETAILS: "project-deployment-details", + UPDATE_LEVELS_SEARCH: "update-levels-search", } as const; diff --git a/apps/customer-portal/webapp/src/layouts/AppLayout.tsx b/apps/customer-portal/webapp/src/layouts/AppLayout.tsx index 180fb97414..f13d367e24 100644 --- a/apps/customer-portal/webapp/src/layouts/AppLayout.tsx +++ b/apps/customer-portal/webapp/src/layouts/AppLayout.tsx @@ -58,8 +58,14 @@ export default function AppLayout({ children }: AppLayoutProps): JSX.Element { const isPendingUpdatesPage = /\/[^/]+\/updates\/pending$/.test( location.pathname, ); + const isUpdateLevelDetailsPage = /\/[^/]+\/updates\/pending\/level\/[^/]+$/.test( + location.pathname, + ); const isDetailsStylePage = - isCaseDetailsPage || isVulnerabilityDetailsPage || isPendingUpdatesPage; + isCaseDetailsPage || + isVulnerabilityDetailsPage || + isPendingUpdatesPage || + isUpdateLevelDetailsPage; return ( diff --git a/apps/customer-portal/webapp/src/models/requests.ts b/apps/customer-portal/webapp/src/models/requests.ts index 65bb868763..628b14e45e 100644 --- a/apps/customer-portal/webapp/src/models/requests.ts +++ b/apps/customer-portal/webapp/src/models/requests.ts @@ -161,6 +161,14 @@ export interface CreateProjectContactRequest { isSecurityContact: boolean; } +// Request body for POST /updates/levels/search. +export interface UpdateLevelsSearchRequest { + startingUpdateLevel: number; + endingUpdateLevel: number; + productName: string; + productVersion: string; +} + // Request body for project time cards search (POST /projects/:projectId/time-cards/search). export interface TimeCardSearchRequest { filters?: { diff --git a/apps/customer-portal/webapp/src/models/responses.ts b/apps/customer-portal/webapp/src/models/responses.ts index 1fc8f52ae2..bea002d980 100644 --- a/apps/customer-portal/webapp/src/models/responses.ts +++ b/apps/customer-portal/webapp/src/models/responses.ts @@ -728,3 +728,44 @@ export interface CreateCallResponse { /** Alias for create/update call request response (shared shape). */ export type CallRequestResponse = CreateCallResponse; + +// Security advisory item inside an update description level. +export interface SecurityAdvisory { + id: string; + overview: string; + severity: string; + description: string; + impact: string; + solution: string; + notes: string; + credits: string; +} + +// Single update description entry within an update level. +export interface UpdateDescriptionLevel { + updateLevel: number; + productName: string; + productVersion: string; + channel: string; + updateType: string; + updateNumber: number; + description: string; + instructions: string; + bugFixes: string; + filesAdded: string; + filesModified: string; + filesRemoved: string; + bundlesInfoChanges: string | null; + dependantReleases: string | null; + timestamp: number; + securityAdvisories: SecurityAdvisory[]; +} + +// Entry for a single update level key from POST /updates/levels/search. +export interface UpdateLevelEntry { + updateType: string; + updateDescriptionLevels: UpdateDescriptionLevel[]; +} + +// Response for POST /updates/levels/search (map keyed by update level string). +export type UpdateLevelsSearchResponse = Record; diff --git a/apps/customer-portal/webapp/src/pages/PendingUpdatesPage.tsx b/apps/customer-portal/webapp/src/pages/PendingUpdatesPage.tsx index e1797dd306..18adc46738 100644 --- a/apps/customer-portal/webapp/src/pages/PendingUpdatesPage.tsx +++ b/apps/customer-portal/webapp/src/pages/PendingUpdatesPage.tsx @@ -17,16 +17,15 @@ import { Box, IconButton, Paper, Stack, Typography } from "@wso2/oxygen-ui"; import { ArrowLeft, RefreshCw } from "@wso2/oxygen-ui-icons-react"; import { useParams, useSearchParams, useNavigate } from "react-router"; -import { useMemo, type JSX } from "react"; -import { useGetRecommendedUpdateLevels } from "@api/useGetRecommendedUpdateLevels"; -import { useGetProductUpdateLevels } from "@api/useGetProductUpdateLevels"; -import { getPendingUpdateLevels } from "@utils/updates"; +import { useCallback, useMemo, type JSX } from "react"; +import { usePostUpdateLevelsSearch } from "@api/usePostUpdateLevelsSearch"; import { PendingUpdatesList } from "@components/updates/pending-updates/PendingUpdatesList"; import PendingUpdatesListSkeleton from "@components/updates/pending-updates/PendingUpdatesListSkeleton"; /** - * PendingUpdatesPage displays pending update levels for a product. - * Matches productName and productBaseVersion from recommended vs product-update-levels APIs. + * PendingUpdatesPage displays pending update level descriptions for a product. + * Reads productName, productBaseVersion, startingUpdateLevel and endingUpdateLevel + * from URL search params and calls POST /updates/levels/search. * * @returns {JSX.Element} The rendered Pending Updates page. */ @@ -37,28 +36,38 @@ export default function PendingUpdatesPage(): JSX.Element { const productName = searchParams.get("productName") ?? ""; const productBaseVersion = searchParams.get("productBaseVersion") ?? ""; + const startParam = searchParams.get("startingUpdateLevel"); + const endParam = searchParams.get("endingUpdateLevel"); + const startingUpdateLevel = Number(startParam ?? "0"); + const endingUpdateLevel = Number(endParam ?? "0"); - const { data: recommendedData } = useGetRecommendedUpdateLevels(); - const { data: productLevelsData, isLoading: isProductLevelsLoading } = - useGetProductUpdateLevels(); - - const recommendedItem = useMemo( - () => - recommendedData?.find( - (r) => - r.productName === productName && - r.productBaseVersion === productBaseVersion, - ), - [recommendedData, productName, productBaseVersion], - ); + const searchRequest = useMemo(() => { + if ( + !productName || + !productBaseVersion || + startParam === null || + endParam === null || + Number.isNaN(startingUpdateLevel) || + Number.isNaN(endingUpdateLevel) + ) { + return null; + } + return { + productName, + productVersion: productBaseVersion, + startingUpdateLevel, + endingUpdateLevel, + }; + }, [ + productName, + productBaseVersion, + startParam, + endParam, + startingUpdateLevel, + endingUpdateLevel, + ]); - const pendingRows = useMemo( - () => - recommendedItem - ? getPendingUpdateLevels(recommendedItem, productLevelsData) - : [], - [recommendedItem, productLevelsData], - ); + const { data, isLoading, isError } = usePostUpdateLevelsSearch(searchRequest); const displayTitle = useMemo(() => { const name = productName || "Product"; @@ -66,10 +75,14 @@ export default function PendingUpdatesPage(): JSX.Element { return ver ? `${name} ${ver}` : name; }, [productName, productBaseVersion]); - const levelRange = - pendingRows.length > 0 - ? `${pendingRows[0].updateLevel} to ${pendingRows[pendingRows.length - 1].updateLevel}` - : null; + const levelRange = useMemo(() => { + if (!data) return null; + const levels = Object.keys(data).map(Number).sort((a, b) => a - b); + if (levels.length === 0) return null; + return levels.length === 1 + ? `Update level ${levels[0]}` + : `Update levels ${levels[0]} to ${levels[levels.length - 1]}`; + }, [data]); const handleBack = () => { if (projectId) { @@ -79,6 +92,19 @@ export default function PendingUpdatesPage(): JSX.Element { } }; + const handleView = useCallback( + (levelKey: string) => { + const params = new URLSearchParams({ + productName, + productBaseVersion, + startingUpdateLevel: String(startingUpdateLevel), + endingUpdateLevel: String(endingUpdateLevel), + }); + navigate(`/${projectId}/updates/pending/level/${levelKey}?${params}`); + }, + [navigate, projectId, productName, productBaseVersion, startingUpdateLevel, endingUpdateLevel], + ); + if (!productName || !productBaseVersion) { return ( @@ -94,9 +120,6 @@ export default function PendingUpdatesPage(): JSX.Element { ); } - const isLoading = - isProductLevelsLoading || (recommendedData === undefined && !pendingRows.length); - return ( {levelRange && ( - Update levels {levelRange} + {levelRange} )} @@ -159,8 +182,9 @@ export default function PendingUpdatesPage(): JSX.Element { ) : ( )} diff --git a/apps/customer-portal/webapp/src/pages/UpdateLevelDetailsPage.tsx b/apps/customer-portal/webapp/src/pages/UpdateLevelDetailsPage.tsx new file mode 100644 index 0000000000..3405769b81 --- /dev/null +++ b/apps/customer-portal/webapp/src/pages/UpdateLevelDetailsPage.tsx @@ -0,0 +1,519 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { + alpha, + Box, + Button, + ButtonGroup, + Card, + CardContent, + Chip, + Divider, + IconButton, + Paper, + Stack, + Typography, + useTheme, +} from "@wso2/oxygen-ui"; +import { ArrowLeft, ExternalLink, RefreshCw } from "@wso2/oxygen-ui-icons-react"; +import { useState, useMemo, type JSX } from "react"; +import { useNavigate, useParams, useSearchParams } from "react-router"; +import { usePostUpdateLevelsSearch } from "@api/usePostUpdateLevelsSearch"; +import { getUpdateTypeChipColor } from "@utils/updates"; +import type { SecurityAdvisory, UpdateDescriptionLevel } from "@models/responses"; +import PendingUpdatesListSkeleton from "@components/updates/pending-updates/PendingUpdatesListSkeleton"; +import EmptyState from "@components/common/empty-state/EmptyState"; +import ErrorStateIcon from "@components/common/error-state/ErrorStateIcon"; + +type FilterType = "all" | "security" | "regular"; + +const FILTER_BUTTONS: { key: FilterType; label: string }[] = [ + { key: "all", label: "All" }, + { key: "security", label: "Security" }, + { key: "regular", label: "Regular" }, +]; + +/** Returns true only for http/https URLs to prevent javascript: or data: URIs. */ +function isSafeUrl(url: string): boolean { + return /^https?:\/\//i.test(url.trim()); +} + +/** + * Parses a JSON-stringified array string into a plain string array. + * Returns empty array on parse failure. + * + * @param {string} raw - The raw JSON string. + * @returns {string[]} Parsed string items. + */ +function parseJsonStringArray(raw: string): string[] { + try { + const parsed = JSON.parse(raw); + return Array.isArray(parsed) ? (parsed as string[]) : []; + } catch { + return []; + } +} + +/** + * Renders a labelled section with pre-wrapped text, supporting `\n` as real line breaks. + * + * @param {{ title: string; content: string }} props - Section heading and raw content string. + * @returns {JSX.Element} The rendered section. + */ +function UpdateSection({ title, content }: { title: string; content: string }): JSX.Element { + const lines = content.split("\n"); + return ( + + + {title} + + + {lines.map((line, i) => ( + + {line || "\u00A0"} + + ))} + + + ); +} + +/** + * Card showing all details for a single update description entry. + * + * @param {{ desc: UpdateDescriptionLevel }} props - The update description item. + * @returns {JSX.Element} The rendered update detail card. + */ +function UpdateDetailCard({ desc }: { desc: UpdateDescriptionLevel }): JSX.Element { + const theme = useTheme(); + const chipColor = getUpdateTypeChipColor(desc.updateType); + const bugFixes = parseJsonStringArray(desc.bugFixes); + const filesModified = parseJsonStringArray(desc.filesModified); + const filesAdded = parseJsonStringArray(desc.filesAdded); + const filesRemoved = parseJsonStringArray(desc.filesRemoved); + + return ( + + + {/* Header row */} + + + + Update Number: {desc.updateNumber} + + + + + + Status + + + Released + + + + + + + + {/* Description */} + {desc.description && ( + + )} + + {/* Instructions */} + {desc.instructions && desc.instructions !== "N/A" && ( + + )} + + {/* Bug Fixes */} + {bugFixes.length > 0 && bugFixes.some((f) => f !== "N/A") && ( + + + Bug Fixes + + + {bugFixes + .filter((f) => f !== "N/A") + .map((fix, i) => + isSafeUrl(fix) ? ( + + + {fix} + + ) : ( + + {fix} + + ), + )} + + + )} + + {/* Files Modified */} + {filesModified.length > 0 && ( + + + Files Modified + + + {filesModified.map((f, i) => ( + + {f} + + ))} + + + )} + + {/* Files Added */} + {filesAdded.length > 0 && ( + + + Files Added + + + {filesAdded.map((f, i) => ( + + {f} + + ))} + + + )} + + {/* Files Removed */} + {filesRemoved.length > 0 && ( + + + Files Removed + + + {filesRemoved.map((f, i) => ( + + {f} + + ))} + + + )} + + {/* Security Advisories */} + {desc.securityAdvisories.length > 0 && ( + + + Security Advisories + + + {desc.securityAdvisories.map((advisory: SecurityAdvisory) => ( + + + + {advisory.id} + + + + + {advisory.overview} + + + + ))} + + + )} + + + + ); +} + +/** + * UpdateLevelDetailsPage shows the full detail for a single update level. + * Reads levelKey from route params and product info from URL search params. + * Re-uses cached POST /updates/levels/search result via usePostUpdateLevelsSearch. + * + * @returns {JSX.Element} The rendered update level detail page. + */ +export default function UpdateLevelDetailsPage(): JSX.Element { + const navigate = useNavigate(); + const { projectId, levelKey } = useParams<{ projectId: string; levelKey: string }>(); + const [searchParams] = useSearchParams(); + const [filter, setFilter] = useState("all"); + + const productName = searchParams.get("productName") ?? ""; + const productBaseVersion = searchParams.get("productBaseVersion") ?? ""; + const startParam = searchParams.get("startingUpdateLevel"); + const endParam = searchParams.get("endingUpdateLevel"); + const startingUpdateLevel = Number(startParam ?? "0"); + const endingUpdateLevel = Number(endParam ?? "0"); + + const searchRequest = useMemo(() => { + if ( + !productName || + !productBaseVersion || + startParam === null || + endParam === null || + Number.isNaN(startingUpdateLevel) || + Number.isNaN(endingUpdateLevel) + ) { + return null; + } + return { productName, productVersion: productBaseVersion, startingUpdateLevel, endingUpdateLevel }; + }, [ + productName, + productBaseVersion, + startParam, + endParam, + startingUpdateLevel, + endingUpdateLevel, + ]); + + const { data, isLoading, isError } = usePostUpdateLevelsSearch(searchRequest); + + const entry = levelKey && data ? data[levelKey] : undefined; + + const filteredDescriptions = useMemo(() => { + if (!entry) return []; + if (filter === "all") return entry.updateDescriptionLevels; + return entry.updateDescriptionLevels.filter((d) => d.updateType === filter); + }, [entry, filter]); + + const handleBack = () => { + if (projectId) { + const params = new URLSearchParams({ + productName, + productBaseVersion, + startingUpdateLevel: String(startingUpdateLevel), + endingUpdateLevel: String(endingUpdateLevel), + }); + navigate(`/${projectId}/updates/pending?${params}`); + } else { + navigate(-1); + } + }; + + return ( + + {/* Page header — same structure as PendingUpdatesPage */} + + + + + + + + + + + Update Level {levelKey} Details + + + {productName} + {productBaseVersion ? ` - Version ${productBaseVersion}` : ""} + + + + + + {/* Content */} + + {isLoading ? ( + + ) : isError ? ( + + + + Failed to load updates. Please try again. + + + ) : !entry ? ( + + + + Level not found. + + + ) : ( + + {/* Product info card */} + + + + + + Product Name + + + {productName || "--"} + + + + + Product Version + + + {productBaseVersion || "--"} + + + + + Released Update Level + + + {levelKey} + + + + + + + {/* Filter buttons */} + + + {FILTER_BUTTONS.map(({ key, label }) => ( + + ))} + + + + {/* Update detail cards */} + {filteredDescriptions.length === 0 ? ( + + ) : ( + + {filteredDescriptions.map((desc) => ( + + ))} + + )} + + )} + + + ); +} diff --git a/apps/customer-portal/webapp/src/pages/UpdatesPage.tsx b/apps/customer-portal/webapp/src/pages/UpdatesPage.tsx index 41b7acbc00..4174980c2c 100644 --- a/apps/customer-portal/webapp/src/pages/UpdatesPage.tsx +++ b/apps/customer-portal/webapp/src/pages/UpdatesPage.tsx @@ -14,14 +14,14 @@ // specific language governing permissions and limitations // under the License. -import { Box, Stack, Typography } from "@wso2/oxygen-ui"; +import { Box, Stack } from "@wso2/oxygen-ui"; import { useParams } from "react-router"; import { useState, useEffect, useRef, type JSX } from "react"; import TabBar from "@components/common/tab-bar/TabBar"; import { UpdatesStatsGrid } from "@components/updates/stat-card-row/UpdatesStatsGrid"; import { UpdateProductGrid } from "@update-cards/UpdateProductGrid"; +import AllUpdatesTab from "@components/updates/all-updates/AllUpdatesTab"; import { useGetRecommendedUpdateLevels } from "@api/useGetRecommendedUpdateLevels"; -import { useGetProductUpdateLevels } from "@api/useGetProductUpdateLevels"; import { useLoader } from "@context/linear-loader/LoaderContext"; import { useErrorBanner } from "@context/error-banner/ErrorBannerContext"; import { useLogger } from "@hooks/useLogger"; @@ -45,8 +45,6 @@ export default function UpdatesPage(): JSX.Element { const hasShownErrorRef = useRef(false); const { data, isLoading, isError } = useGetRecommendedUpdateLevels(); - // Prefetch in background for pending updates detail page. - useGetProductUpdateLevels(); const isUpdatesLoading = isLoading || (!data && !isError); @@ -94,11 +92,7 @@ export default function UpdatesPage(): JSX.Element { ); } - return ( - - All updates content - - ); + return ; }; return ( diff --git a/apps/customer-portal/webapp/src/utils/__tests__/updateLevelsReportPdf.test.ts b/apps/customer-portal/webapp/src/utils/__tests__/updateLevelsReportPdf.test.ts new file mode 100644 index 0000000000..fa29da18f7 --- /dev/null +++ b/apps/customer-portal/webapp/src/utils/__tests__/updateLevelsReportPdf.test.ts @@ -0,0 +1,117 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { describe, it, expect } from "vitest"; +import { getUpdateLevelsReportData } from "@utils/updateLevelsReportPdf"; + +const mockData = { + "2": { + updateType: "regular", + updateDescriptionLevels: [ + { + updateLevel: 2, + productName: "WSO2 API Manager", + productVersion: "4.4.0", + channel: "full", + updateType: "regular", + updateNumber: 100, + description: "Fix.", + instructions: "N/A", + bugFixes: "[]", + filesAdded: "[]", + filesModified: "[]", + filesRemoved: "[]", + bundlesInfoChanges: null, + dependantReleases: null, + timestamp: 1705939200000, + securityAdvisories: [], + }, + ], + }, + "3": { + updateType: "security", + updateDescriptionLevels: [ + { + updateLevel: 3, + productName: "WSO2 API Manager", + productVersion: "4.4.0", + channel: "full", + updateType: "security", + updateNumber: 101, + description: "Security fix.", + instructions: "N/A", + bugFixes: "[]", + filesAdded: "[]", + filesModified: "[]", + filesRemoved: "[]", + bundlesInfoChanges: null, + dependantReleases: null, + timestamp: 1706025600000, + securityAdvisories: [], + }, + ], + }, +}; + +describe("getUpdateLevelsReportData", () => { + it("returns structured report data with expected fields", () => { + const result = getUpdateLevelsReportData({ + productName: "WSO2 API Manager", + productVersion: "4.4.0", + startLevel: 2, + endLevel: 19, + data: mockData, + }); + + expect(result.productName).toBe("WSO2 API Manager"); + expect(result.productVersion).toBe("4.4.0"); + expect(result.startLevel).toBe(2); + expect(result.endLevel).toBe(19); + expect(result.securityCount).toBe(1); + expect(result.regularCount).toBe(1); + expect(result.totalUpdates).toBe(2); + expect(result.levelCount).toBe(2); + expect(result.levelsRange).toBe("2 - 3"); + expect(result.tableRows).toHaveLength(2); + }); + + it("formats release dates correctly in UTC", () => { + const result = getUpdateLevelsReportData({ + productName: "Product", + productVersion: "1.0", + startLevel: 2, + endLevel: 3, + data: mockData, + }); + + // mockData level 2 has timestamp 1705939200000 = Jan 22, 2024 UTC + expect(result.tableRows[0].releaseDate).toBe("Jan 22, 2024"); + // mockData level 3 has timestamp 1706025600000 = Jan 23, 2024 UTC + expect(result.tableRows[1].releaseDate).toBe("Jan 23, 2024"); + }); + + it("throws when data is empty", () => { + expect(() => + getUpdateLevelsReportData({ + productName: "Product", + productVersion: "1.0", + startLevel: 1, + endLevel: 5, + data: {}, + }), + ).toThrow(/No update data/); + }); +}); diff --git a/apps/customer-portal/webapp/src/utils/updateLevelsReportPdf.ts b/apps/customer-portal/webapp/src/utils/updateLevelsReportPdf.ts new file mode 100644 index 0000000000..b766b77dcf --- /dev/null +++ b/apps/customer-portal/webapp/src/utils/updateLevelsReportPdf.ts @@ -0,0 +1,218 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { jsPDF } from "jspdf"; +import autoTable from "jspdf-autotable"; +import type { UpdateLevelsSearchResponse } from "@models/responses"; + +export interface UpdateLevelsReportParams { + productName: string; + productVersion: string; + startLevel: number; + endLevel: number; + data: UpdateLevelsSearchResponse; +} + +export interface UpdateLevelsReportTableRow { + levelKey: string; + typeLabel: string; + updatesCount: number; + releaseDate: string; + applied: string; +} + +export interface UpdateLevelsReportData { + generatedStr: string; + productName: string; + productVersion: string; + startLevel: number; + endLevel: number; + securityCount: number; + regularCount: number; + mixedCount: number; + totalUpdates: number; + levelCount: number; + levelsRange: string; + tableRows: UpdateLevelsReportTableRow[]; +} + +/** + * Formats a Unix timestamp (ms) as "MMM DD, YYYY" in UTC. + * + * @param {number} ts - Timestamp in milliseconds. + * @returns {string} Formatted date string. + */ +function formatReleaseDate(ts: number): string { + const d = new Date(ts); + const months = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ]; + const m = months[d.getUTCMonth()]; + const day = d.getUTCDate(); + const year = d.getUTCFullYear(); + return `${m} ${day}, ${year}`; +} + +/** + * Computes structured report data for the Update Levels Report. + * Used by UpdateLevelsReportModal for in-app display. + * + * @param {UpdateLevelsReportParams} params - Report parameters and search data. + * @returns {UpdateLevelsReportData} Structured report data. + */ +export function getUpdateLevelsReportData(params: UpdateLevelsReportParams): UpdateLevelsReportData { + const { productName, productVersion, startLevel, endLevel, data } = params; + + const entries = Object.entries(data).sort( + ([a], [b]) => Number(a) - Number(b), + ); + + if (entries.length === 0) { + throw new Error("No update data to generate report."); + } + + const now = new Date(); + const generatedStr = now.toLocaleString("en-US", { + year: "numeric", + month: "long", + day: "numeric", + hour: "numeric", + minute: "2-digit", + hour12: true, + }); + + const securityCount = entries.filter(([, e]) => e.updateType === "security").length; + const regularCount = entries.filter(([, e]) => e.updateType === "regular").length; + const mixedCount = entries.filter(([, e]) => e.updateType === "mixed").length; + const totalUpdates = entries.reduce( + (sum, [, e]) => sum + e.updateDescriptionLevels.length, + 0, + ); + + const levelCount = entries.length; + const levelsRange = + levelCount === 1 + ? `${entries[0][0]}` + : `${entries[0][0]} - ${entries[entries.length - 1][0]}`; + + const tableRows: UpdateLevelsReportTableRow[] = entries.map(([levelKey, entry]) => { + const firstDesc = entry.updateDescriptionLevels[0]; + const releaseDate = firstDesc?.timestamp + ? formatReleaseDate(firstDesc.timestamp) + : "N/A"; + const typeLabel = + entry.updateType.charAt(0).toUpperCase() + entry.updateType.slice(1); + return { + levelKey, + typeLabel, + updatesCount: entry.updateDescriptionLevels.length, + releaseDate, + applied: "N/A", + }; + }); + + return { + generatedStr, + productName, + productVersion, + startLevel, + endLevel, + securityCount, + regularCount, + mixedCount, + totalUpdates, + levelCount, + levelsRange, + tableRows, + }; +} + +/** + * Generates and downloads an Update Levels Report PDF using jspdf and jspdf-autotable. + * + * @param {UpdateLevelsReportData} reportData - Structured report data from getUpdateLevelsReportData. + */ +export function generateUpdateLevelsReportPdf(reportData: UpdateLevelsReportData): void { + const doc = new jsPDF(); + + doc.setFontSize(18); + doc.text("Update Levels Report", 14, 20); + + doc.setFontSize(10); + doc.text(`Generated on: ${reportData.generatedStr}`, 14, 28); + + doc.setFontSize(12); + doc.text("Search Criteria", 14, 38); + doc.setFontSize(10); + doc.text(`Product: ${reportData.productName}`, 14, 45); + doc.text(`Version: ${reportData.productVersion}`, 14, 52); + doc.text(`Update Level Range: ${reportData.startLevel} to ${reportData.endLevel}`, 14, 59); + doc.text("View Mode: All Updates", 14, 66); + doc.text(`Total Updates: ${reportData.totalUpdates}`, 14, 76); + doc.text(`Update Levels: ${reportData.levelCount} levels (${reportData.levelsRange})`, 14, 83); + + doc.setFontSize(12); + doc.text("Update Levels Summary", 14, 95); + doc.setFontSize(10); + doc.text(`Security Updates: ${reportData.securityCount}`, 14, 102); + doc.text(`Regular Updates: ${reportData.regularCount}`, 14, 109); + doc.text(`Mixed Updates: ${reportData.mixedCount}`, 14, 116); + doc.text("Applied Updates: N/A", 14, 123); + doc.text(`Pending Updates: ${reportData.levelCount}`, 14, 130); + + doc.setFontSize(12); + doc.text("Update Levels Details", 14, 142); + + const tableData = reportData.tableRows.map((row) => [ + row.levelKey, + row.typeLabel, + String(row.updatesCount), + row.releaseDate, + row.applied, + ]); + + autoTable(doc, { + startY: 148, + head: [["Level", "Type", "Updates", "Release Date", "Applied"]], + body: tableData, + theme: "grid", + headStyles: { fillColor: [100, 100, 100], fontSize: 9 }, + bodyStyles: { fontSize: 9 }, + columnStyles: { + 0: { cellWidth: 20 }, + 1: { cellWidth: 35 }, + 2: { cellWidth: 25 }, + 3: { cellWidth: 45 }, + 4: { cellWidth: 25 }, + }, + margin: { left: 14 }, + }); + + const totalPages = doc.getNumberOfPages(); + for (let i = 1; i <= totalPages; i++) { + doc.setPage(i); + doc.setFontSize(8); + doc.text( + `${reportData.productName} ${reportData.productVersion} - Update Levels Report Page ${i} of ${totalPages}`, + 14, + doc.internal.pageSize.getHeight() - 10, + ); + } + + const fileName = `Update-Levels-Report-${reportData.productName}-${reportData.productVersion}-${reportData.startLevel}-${reportData.endLevel}.pdf`; + doc.save(fileName); +} diff --git a/apps/customer-portal/webapp/src/utils/updates.ts b/apps/customer-portal/webapp/src/utils/updates.ts index 5204f48112..70087c70fb 100644 --- a/apps/customer-portal/webapp/src/utils/updates.ts +++ b/apps/customer-portal/webapp/src/utils/updates.ts @@ -15,12 +15,25 @@ // under the License. import { UPDATES_STATS } from "@constants/updatesConstants"; +import type { StatCardColor } from "@constants/dashboardConstants"; import type { ProductUpdateLevelsResponse, RecommendedUpdateLevelItem, UpdatesStats, } from "@models/responses"; +/** + * Returns the StatCard-compatible chip colour for an update type. + * "security" maps to "error" (red); all other types (e.g. "regular") map to "success" (green). + * + * @param {string} updateType - The update type string from the API. + * @returns {StatCardColor} The chip colour token. + */ +export const getUpdateTypeChipColor = (updateType: string): StatCardColor => { + if (updateType === "security") return "error"; + return "success"; +}; + /** Pending update level row for display. */ export interface PendingUpdateLevelRow { updateLevel: number;