@@ -5,6 +5,86 @@ $(function () {
55 storeName : storeName ,
66 } ) ;
77
8+ /* ---------------- CSV Download for Module Scores Table ---------------- */
9+
10+ // Use both delegated and direct handlers for maximum compatibility
11+ $ ( document ) . on ( "click" , "#btn-module-csv" , function ( e ) {
12+ e . preventDefault ( ) ;
13+ e . stopPropagation ( ) ;
14+ downloadModuleCSV ( ) ;
15+ } ) ;
16+
17+ // Also set up a direct handler once the button appears
18+ function setupDirectHandler ( ) {
19+ const btn = document . getElementById ( "btn-module-csv" ) ;
20+ if ( btn ) {
21+ btn . addEventListener ( "click" , function ( e ) {
22+ e . preventDefault ( ) ;
23+ e . stopPropagation ( ) ;
24+ downloadModuleCSV ( ) ;
25+ } ) ;
26+ } else {
27+ setTimeout ( setupDirectHandler , 1000 ) ;
28+ }
29+ }
30+ setTimeout ( setupDirectHandler , 100 ) ;
31+
32+ function downloadModuleCSV ( ) {
33+ const table = $ ( "#module-scores-table" ) ;
34+ const headers = [ ] ;
35+ const rows = [ ] ;
36+
37+ // Get module name from the selectize dropdown
38+ const selectize = $ ( "#select-for-modules" ) [ 0 ] ?. selectize ;
39+ const moduleName = selectize ? selectize . getItem ( selectize . getValue ( ) ) ?. text ( ) : "module" ;
40+ const sanitizedModuleName = moduleName . replace ( / [ ^ a - z 0 - 9 ] / gi, '_' ) . replace ( / _ + / g, '_' ) ;
41+
42+ // Get headers
43+ $ ( "#mst-header-row th" ) . each ( function ( ) {
44+ headers . push (
45+ $ ( this )
46+ . text ( )
47+ . trim ( )
48+ . replace ( / \s * \( \? \) \s * / g, "" ) ,
49+ ) ;
50+ } ) ;
51+
52+ console . log ( "Headers:" , headers ) ;
53+
54+ // Get data rows
55+ $ ( "#mst-body tr" ) . each ( function ( ) {
56+ const row = [ ] ;
57+ $ ( this )
58+ . find ( "td" )
59+ . each ( function ( ) {
60+ const text = $ ( this ) . text ( ) . trim ( ) ;
61+ // Escape commas and quotes in CSV
62+ const escaped =
63+ text . includes ( "," ) || text . includes ( '"' )
64+ ? `"${ text . replace ( / " / g, '""' ) } "`
65+ : text ;
66+ row . push ( escaped ) ;
67+ } ) ;
68+ rows . push ( row . join ( "," ) ) ;
69+ } ) ;
70+
71+ // Create CSV content
72+ const csvContent = [ headers . join ( "," ) , ...rows ] . join ( "\n" ) ;
73+
74+ // Create download link
75+ const blob = new Blob ( [ csvContent ] , { type : "text/csv;charset=utf-8;" } ) ;
76+ const link = document . createElement ( "a" ) ;
77+ const url = URL . createObjectURL ( blob ) ;
78+
79+ link . setAttribute ( "href" , url ) ;
80+ link . setAttribute ( "download" , `MS-Overview-${ sanitizedModuleName } .csv` ) ;
81+ link . style . visibility = "hidden" ;
82+
83+ document . body . appendChild ( link ) ;
84+ link . click ( ) ;
85+ document . body . removeChild ( link ) ;
86+ URL . revokeObjectURL ( url ) ;
87+ }
888 // Returns weeks start and end dates
989 function getWeeksDates ( start , end ) {
1090 var sDate ;
0 commit comments