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