Bug 13618: Add html filters to all the variables
[koha.git] / koha-tmpl / intranet-tmpl / prog / en / modules / tools / quotes-upload.tt
1 [% USE raw %]
2 [% USE Asset %]
3 [% SET footerjs = 1 %]
4     [% INCLUDE 'doc-head-open.inc' %]
5     <title>Koha &rsaquo; Tools &rsaquo; Quote uploader</title>
6     [% INCLUDE 'doc-head-close.inc' %]
7     [% Asset.css("css/uploader.css") | $raw %]
8     [% Asset.css("css/quotes.css") | $raw %]
9     [% Asset.css("css/datatables.css") | $raw %]
10 </head>
11
12 <body id="tools_quotes" class="tools">
13 [% INCLUDE 'header.inc' %]
14 [% INCLUDE 'cat-search.inc' %]
15
16 <div id="breadcrumbs"><a href="/cgi-bin/koha/mainpage.pl">Home</a> &rsaquo; <a href="/cgi-bin/koha/tools/tools-home.pl">Tools</a> &rsaquo; <a href="/cgi-bin/koha/tools/quotes.pl">Quote editor</a> &rsaquo; Quote uploader</div>
17
18 <div id="doc3" class="yui-t2">
19     <div id="bd">
20         <div id="yui-main">
21             <div class="yui-b">
22                 [% INCLUDE 'quotes-upload-toolbar.inc' %]
23                 <h2>Quote uploader</h2>
24                 <div id="instructions">
25                 <fieldset id="file_uploader_help" class="rows">
26                     <legend>Instructions</legend>
27                     <div id="file_uploader_inst">
28                         <ul>
29                         <li>The quote uploader accepts standard csv files with two columns: "source","text"</li>
30                         <li>Click the "Choose File" button and select the csv file to be uploaded.</li>
31                         <li>The file will be imported into an editable table for review prior to saving.</li>
32                         </ul>
33                     </div>
34                     <div id="file_editor_inst">
35                         <ul>
36                         <li>Click on any field to edit the contents; Press the &lt;Enter&gt; key to save edit.</li>
37                         <li>Click on one or more quote numbers to select entire quotes for deletion; Click the 'Delete Quote(s)' button to delete selected quotes.</li>
38                         <li>Click the 'Save Quotes' button in the toolbar to save the entire batch of quotes.</li>
39                         </ul>
40                     </div>
41                 </fieldset>
42                 </div>
43                 <fieldset id="file_uploader" class="rows">
44                     <legend>Upload quotes</legend>
45                     <div id="file_upload">
46                         <input type="file" name="file" />
47                         <button id="cancel_upload" style="display:none">Cancel upload</button>
48                         <div id="progress_bar"><div class="percent">0%</div></div>
49                     </div>
50                 </fieldset>
51                 <table id="quotes_editor" style="visibility: hidden;">
52                 <thead>
53                     <tr>
54                         <th>Source</th>
55                         <th>Text</th>
56                         <th>Actions</th>
57                     </tr>
58                 </thead>
59                 <tbody>
60                     <!-- tbody content is generated by DataTables -->
61                     <tr>
62                         <td></td>
63                         <td>Loading data...</td>
64                         <td></td>
65                     </tr>
66                 </tbody>
67                 </table>
68                 <fieldset id="footer" class="action" style="visibility: hidden;">
69                 </fieldset>
70             </div>
71         </div>
72     <div class="yui-b noprint">
73         [% INCLUDE 'tools-menu.inc' %]
74     </div>
75 </div>
76
77 [% MACRO jsinclude BLOCK %]
78     [% Asset.js("js/tools-menu.js") | $raw %]
79     [% INCLUDE 'datatables.inc' %]
80     [% Asset.js("lib/jquery/plugins/jquery.jeditable.mini.js") | $raw %]
81     <script type="text/javascript">
82         var oTable; //DataTable object
83         $(document).ready(function() {
84
85             $("#cancel_upload").on("click",function(e){
86                 e.preventDefault();
87                 fnAbortRead();
88             });
89             $("#cancel_quotes").on("click",function(){
90                 return confirm( _("Are you sure you want to cancel this import?") );
91             });
92
93         // Credits:
94         // FileReader() code copied and hacked from:
95         // http://www.html5rocks.com/en/tutorials/file/dndfiles/
96         // fnCSVToArray() gratefully borrowed from:
97         // http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
98
99         var reader;
100         var progress = document.querySelector('.percent');
101         $("#server_response").hide();
102
103         function yuiGetData() {
104             fnGetData(document.getElementById('quotes_editor'));
105         }
106
107         function fnAbortRead() {
108             reader.abort();
109         }
110
111         function fnErrorHandler(evt) {
112             switch(evt.target.error.code) {
113                 case evt.target.error.NOT_FOUND_ERR:
114                     alert(_("File Not Found!"));
115                     break;
116                 case evt.target.error.NOT_READABLE_ERR:
117                     alert(_("File is not readable"));
118                     break;
119                 case evt.target.error.ABORT_ERR:
120                     break; // noop
121                 default:
122                     alert(_("An error occurred reading this file."));
123             };
124         }
125
126         function fnUpdateProgress(evt) {
127             // evt is an ProgressEvent.
128             if (evt.lengthComputable) {
129                 var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
130                 // Increase the progress bar length.
131                 if (percentLoaded < 100) {
132                     progress.style.width = percentLoaded + '%';
133                     progress.textContent = percentLoaded + '%';
134                 }
135             }
136         }
137
138         function fnCSVToArray( strData, strDelimiter ){
139             // This will parse a delimited string into an array of
140             // arrays. The default delimiter is the comma, but this
141             // can be overriden in the second argument.
142
143             // Check to see if the delimiter is defined. If not,
144             // then default to comma.
145             strDelimiter = (strDelimiter || ",");
146
147             // Create a regular expression to parse the CSV values.
148             var objPattern = new RegExp(
149             (
150                 // Delimiters.
151                 "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
152                 // Quoted fields.
153                 "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
154                 // Standard fields.
155                 "([^\"\\" + strDelimiter + "\\r\\n]*))"
156             ),
157                 "gi"
158             );
159
160             // Create an array to hold our data. Give the array
161             // a default empty first row.
162             var arrData = [[]];
163
164             // Create an array to hold our individual pattern
165             // matching groups.
166             var arrMatches = null;
167
168             // Keep looping over the regular expression matches
169             // until we can no longer find a match.
170             while (arrMatches = objPattern.exec( strData )){
171
172                 // Get the delimiter that was found.
173                 var strMatchedDelimiter = arrMatches[ 1 ];
174
175                 // Check to see if the given delimiter has a length
176                 // (is not the start of string) and if it matches
177                 // field delimiter. If it does not, then we know
178                 // that this delimiter is a row delimiter.
179                 if ( strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter) ){
180                     // Since we have reached a new row of data,
181                     // add an empty row to our data array.
182                     // Note: if there is not more data, we will have to remove this row later
183                     arrData.push( [] );
184                 }
185
186                 // Now that we have our delimiter out of the way,
187                 // let's check to see which kind of value we
188                 // captured (quoted or unquoted).
189                 if (arrMatches[ 2 ]){
190                     // We found a quoted value. When we capture
191                     // this value, unescape any double quotes.
192                     var strMatchedValue = arrMatches[ 2 ].replace(
193                     new RegExp( "\"\"", "g" ),
194                         "\""
195                     );
196                 } else if (arrMatches[3]){
197                     // We found a non-quoted value.
198                     var strMatchedValue = arrMatches[ 3 ];
199                 } else {
200                     // There is no more valid data so remove the row we added earlier
201                     // Is there a better way? Perhaps a look-ahead regexp?
202                     arrData.splice(arrData.length-1, 1);
203                 }
204
205                 // Now that we have our value string, let's add
206                 // it to the data array.
207                 arrData[ arrData.length - 1 ].push( strMatchedValue );
208             }
209
210             // Return the parsed data.
211             return( arrData );
212         }
213
214         function fnDataTable(aaData) {
215             for(var i=0; i<aaData.length; i++) {
216                 aaData[i].unshift(i+1); // Add a column w/quote number
217             }
218
219             /* Transition from the quote file uploader to the quote file editor interface */
220             $('#toolbar').css("visibility","visible");
221             $('#toolbar').css("position","");
222             $('#file_editor_inst').css("visibility", "visible");
223             $('#file_editor_inst').css("position", "");
224             $('#file_uploader_inst').css("visibility", "hidden");
225             $('#save_quotes').css("visibility","visible");
226             $('#file_uploader').css("visibility","hidden");
227             $('#file_uploader').css("position","absolute");
228             $('#file_uploader').css("top","-150px");
229             $('#quotes_editor').css("visibility","visible");
230             $("#save_quotes").on("click", yuiGetData);
231             $("#delete_quote").on("click", fnClickDeleteRow);
232
233             oTable = $('#quotes_editor').dataTable( {
234                 "bAutoWidth"        : false,
235                 "bPaginate"         : true,
236                 "bSort"             : false,
237                 "sPaginationType"   : "full_numbers",
238                 "sDom": '<"top pager"iflp>rt<"bottom pager"flp><"clear">',
239                 "aaData"            : aaData,
240                 "aoColumns"         : [
241                     {
242                         "sTitle"  : _("Number"),
243                         "sWidth"  : "2%",
244                     },
245                     {
246                         "sTitle"  : _("Source"),
247                         "sWidth"  : "15%",
248                     },
249                     {
250                         "sTitle"  : _("Quote"),
251                         "sWidth"  : "83%",
252                     },
253                 ],
254                "fnPreDrawCallback": function(oSettings) {
255                     return true;
256                 },
257                 "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
258                     /* do foo on various cells in the current row */
259                     var quoteNum = $('td', nRow)[0].innerHTML;
260                     $(nRow).attr("id", quoteNum); /* set row ids to quote number */
261                     $('td:eq(0)', nRow).click(function() {$(this.parentNode).toggleClass('selected',this.clicked);}); /* add row selectors */
262                     $('td:eq(0)', nRow).attr("title", _("Click ID to select/deselect quote"));
263                     /* apply no_edit id to noEditFields */
264                     noEditFields = [0]; /* number */
265                     for (i=0; i<noEditFields.length; i++) {
266                         $('td', nRow)[noEditFields[i]].setAttribute("id","no_edit");
267                     }
268                     return nRow;
269                 },
270                "fnDrawCallback": function(oSettings) {
271                     /* Apply the jEditable handlers to the table on all fields w/o the no_edit id */
272                     $('#quotes_editor tbody td[id!="no_edit"]').editable( function(value, settings) {
273                             var cellPosition = oTable.fnGetPosition( this );
274                             oTable.fnUpdate(value, cellPosition[0], cellPosition[1], false, false);
275                             return(value);
276                         },
277                         {
278                         "callback"      : function( sValue, y ) {
279                                               oTable.fnDraw(false); /* no filter/sort or we lose our pagination */
280                                           },
281                         "height"        : "14px",
282                     });
283                },
284             });
285             $('#footer').css("visibility","visible");
286         }
287
288         function fnHandleFileSelect(evt) {
289             // Reset progress indicator on new file selection.
290             progress.style.width = '0%';
291             progress.textContent = '0%';
292
293             reader = new FileReader();
294             reader.onerror = fnErrorHandler;
295             reader.onprogress = fnUpdateProgress;
296             reader.onabort = function(e) {
297                 alert(_("File read cancelled"));
298                 parent.location='quotes-upload.pl';
299             };
300             reader.onloadstart = function(e) {
301                 $('#cancel_upload').show();
302                 $('#progress_bar').addClass("loading");
303             };
304             reader.onload = function(e) {
305                 // Ensure that the progress bar displays 100% at the end.
306                 progress.style.width = '100%';
307                 progress.textContent = '100%';
308                 $('#cancel_upload').hide();
309                 quotes = fnCSVToArray(e.target.result, ',');
310                 fnDataTable(quotes);
311             }
312
313             // perform various sanity checks on the target file prior to uploading...
314             var fileType = evt.target.files[0].type || 'unknown';
315             var fileSizeInK = Math.round(evt.target.files[0].size/1024);
316
317             if (!fileType.match(/comma-separated-values|csv|excel|calc/i)) {
318                 alert(_("Uploads limited to csv. Incorrect filetype: %s").format(fileType));
319                 parent.location='quotes-upload.pl';
320                 return;
321             }
322             if (fileSizeInK > 512) {
323                 if (!confirm(_("%s %s KB Do you really want to upload this file?").format(evt.target.files[0].name, fileSizeInK))) {
324                     parent.location='quotes-upload.pl';
325                     return;
326                 }
327             }
328             // Read in the image file as a text string.
329             reader.readAsText(evt.target.files[0]);
330         }
331
332         $('#file_upload').one('change', fnHandleFileSelect);
333
334         });
335
336         function fnGetData(element) {
337             var jqXHR = $.ajax({
338                 url         : "/cgi-bin/koha/tools/quotes/quotes-upload_ajax.pl",
339                 type        : "POST",
340                 contentType : "application/x-www-form-urlencoded", // we must claim this mimetype or CGI will not decode the URL encoding
341                 dataType    : "json",
342                 data        : {
343                                 "quote"     : encodeURI ( JSON.stringify(oTable.fnGetData()) ),
344                                 "action"    : "add",
345                               },
346                 success     : function(){
347                     var response = JSON.parse(jqXHR.responseText);
348                     if (response.success) {
349                         alert(_("%s quotes saved.").format(response.records));
350                         window.location.reload(true);   // is this the best route?
351                     } else {
352                         alert(_("%s quotes saved, but an error has occurred. Please ask your administrator to check the server log for more details.").format(response.records));
353                         window.location.reload(true);   // is this the best route?
354                     }
355                   },
356             });
357         }
358
359         function fnClickDeleteRow() {
360             var idsToDelete = oTable.$('.selected').map(function() {
361                   return this.id;
362             }).get().join(', ');
363             if (!idsToDelete) {
364                 alert(_("Please select a quote(s) by clicking the quote id(s) you desire to delete."));
365             }
366             else if (confirm(_("Are you sure you wish to delete quote(s) %s?").format(idsToDelete))) {
367                 oTable.$('.selected').each(function(){
368                     oTable.fnDeleteRow(this);
369                 });
370             }
371         }
372     </script>
373 [% END %]
374
375 [% INCLUDE 'intranet-bottom.inc' %]