005cdd0e682f3f9baa380d9f4b8e253cdf3ae90a
[kivitendo-erp.git] / js / kivi.js
1 namespace("kivi", function(ns) {
2   "use strict";
3
4   ns._locale = {};
5   ns._date_format   = {
6     sep: '.',
7     y:   2,
8     m:   1,
9     d:   0
10   };
11   ns._time_format = {
12     sep: ':',
13     h: 0,
14     m: 1,
15   };
16   ns._number_format = {
17     decimalSep:  ',',
18     thousandSep: '.'
19   };
20
21   ns.setup_formats = function(params) {
22     var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
23     if (res) {
24       ns._date_format                      = { sep: res[2] };
25       ns._date_format[res[1].substr(0, 1)] = 0;
26       ns._date_format[res[3].substr(0, 1)] = 1;
27       ns._date_format[res[4].substr(0, 1)] = 2;
28     }
29
30     res = (params.times || "").match(/^([hm]+)([^a-z])([hm]+)$/);
31     if (res) {
32       ns._time_format                      = { sep: res[2] };
33       ns._time_format[res[1].substr(0, 1)] = 0;
34       ns._time_format[res[3].substr(0, 1)] = 1;
35     }
36
37     res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
38     if (res)
39       ns._number_format = {
40         decimalSep:  res[2],
41         thousandSep: res[1]
42       };
43   };
44
45   ns.parse_date = function(date) {
46     if (date === undefined)
47       return undefined;
48
49     if (date === '')
50       return null;
51
52     if (date === '0' || date === '00')
53       return new Date();
54
55     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
56     var today = new Date();
57
58     // without separator?
59     // assume fixed pattern, and extract parts again
60     if (parts.length == 1) {
61       date  = parts[0];
62       parts = date.match(/../g);
63       if (date.length == 8) {
64         parts[ns._date_format.y] += parts.splice(ns._date_format.y + 1, 1)
65       }
66       else
67       if (date.length == 6 || date.length == 4) {
68       }
69       else
70       if (date.length == 1 || date.length == 2) {
71         parts = []
72         parts[ ns._date_format.y ] = today.getFullYear();
73         parts[ ns._date_format.m ] = today.getMonth() + 1;
74         parts[ ns._date_format.d ] = date;
75       }
76       else {
77         return undefined;
78       }
79     }
80
81     if (parts.length == 3) {
82       var year = +parts[ ns._date_format.y ] || 0 * 1 || (new Date()).getFullYear();
83       if (year > 9999)
84         return undefined;
85       if (year < 100) {
86         year += year > 70 ? 1900 : 2000;
87       }
88       date = new Date(
89         year,
90         (parts[ ns._date_format.m ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
91         (parts[ ns._date_format.d ] || today.getDate()) * 1
92       );
93     } else if (parts.length == 2) {
94       date = new Date(
95         (new Date()).getFullYear(),
96         (parts[ (ns._date_format.m > ns._date_format.d) * 1 ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
97         (parts[ (ns._date_format.d > ns._date_format.m) * 1 ] || today.getDate()) * 1
98       );
99     } else
100       return undefined;
101
102     return isNaN(date.getTime()) ? undefined : date;
103   };
104
105   ns.format_date = function(date) {
106     if (isNaN(date.getTime()))
107       return undefined;
108
109     var parts = [ "", "", "" ]
110     parts[ ns._date_format.y ] = date.getFullYear();
111     parts[ ns._date_format.m ] = (date.getMonth() <  9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
112     parts[ ns._date_format.d ] = (date.getDate()  < 10 ? "0" : "") + date.getDate();
113     return parts.join(ns._date_format.sep);
114   };
115
116   ns.parse_time = function(time) {
117     var now = new Date();
118
119     if (time === undefined)
120       return undefined;
121
122     if (time === '')
123       return null;
124
125     if (time === '0')
126       return now;
127
128     // special case 1: military time in fixed "hhmm" format
129     if (time.length == 4) {
130       var res = time.match(/(\d\d)(\d\d)/);
131       if (res) {
132         now.setHours(res[1], res[2]);
133         return now;
134       } else {
135         return undefined;
136       }
137     }
138
139     var parts = time.replace(/\s+/g, "").split(ns._time_format.sep);
140     if (parts.length == 2) {
141       for (var idx in parts) {
142         if (Number.isNaN(Number.parseInt(parts[idx])))
143           return undefined;
144       }
145       now.setHours(parts[ns._time_format.h], parts[ns._time_format.m]);
146       return now;
147     } else
148       return undefined;
149   }
150
151   ns.format_time = function(date) {
152     if (isNaN(date.getTime()))
153       return undefined;
154
155     var parts = [ "", "" ]
156     parts[ ns._time_format.h ] = date.getHours().toString().padStart(2, '0');
157     parts[ ns._time_format.m ] = date.getMinutes().toString().padStart(2, '0');
158     return parts.join(ns._time_format.sep);
159   };
160
161   ns.parse_amount = function(amount) {
162     if (amount === undefined)
163       return undefined;
164
165     if (amount === '')
166       return null;
167
168     if (ns._number_format.decimalSep == ',')
169       amount = amount.replace(/\./g, "").replace(/,/g, ".");
170
171     amount = amount.replace(/[\',]/g, "");
172
173     // Make sure no code wich is not a math expression ends up in eval().
174     if (!amount.match(/^[0-9 ()\-+*/.]*$/))
175       return undefined;
176
177     amount = amount.replace(/^0+(\d+)/, '$1');
178
179     /* jshint -W061 */
180     try {
181       return eval(amount);
182     } catch (err) {
183       return undefined;
184     }
185   };
186
187   ns.round_amount = function(amount, places) {
188     var neg  = amount >= 0 ? 1 : -1;
189     var mult = Math.pow(10, places + 1);
190     var temp = Math.abs(amount) * mult;
191     var diff = Math.abs(1 - temp + Math.floor(temp));
192     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
193     var dec  = temp % 10;
194     temp    += dec >= 5 ? 10 - dec: dec * -1;
195
196     return neg * temp / mult;
197   };
198
199   ns.format_amount = function(amount, places) {
200     amount = amount || 0;
201
202     if ((places !== undefined) && (places >= 0))
203       amount = ns.round_amount(amount, Math.abs(places));
204
205     var parts = ("" + Math.abs(amount)).split(/\./);
206     var intg  = parts[0];
207     var dec   = parts.length > 1 ? parts[1] : "";
208     var sign  = amount  < 0      ? "-"      : "";
209
210     if (places !== undefined) {
211       while (dec.length < Math.abs(places))
212         dec += "0";
213
214       if ((places > 0) && (dec.length > Math.abs(places)))
215         dec = d.substr(0, places);
216     }
217
218     if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
219       var len   = ((intg.length + 2) % 3) + 1,
220           start = len,
221           res   = intg.substr(0, len);
222       while (start < intg.length) {
223         res   += ns._number_format.thousandSep + intg.substr(start, 3);
224         start += 3;
225       }
226
227       intg = res;
228     }
229
230     var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
231
232     return sign + intg + sep + dec;
233   };
234
235   ns.t8 = function(text, params) {
236     text = ns._locale[text] || text;
237     var key, value
238
239     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
240       var len = params.length;
241
242       for(var i=0; i<len; ++i) {
243         key = i + 1;
244         value = params[i];
245         text = text.split("#"+ key).join(value);
246       }
247     }
248     else if( typeof params == 'object' ) {
249       for(key in params) {
250         value = params[key];
251         text = text.split("#{"+ key +"}").join(value);
252       }
253     }
254
255     return text;
256   };
257
258   ns.setupLocale = function(locale) {
259     ns._locale = locale;
260   };
261
262   ns.set_focus = function(element) {
263     var $e = $(element).eq(0);
264     if ($e.data('ckeditorInstance'))
265       ns.focus_ckeditor_when_ready($e);
266     else
267       $e.focus();
268   };
269
270   ns.focus_ckeditor_when_ready = function(element) {
271     $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
272   };
273
274   ns.focus_ckeditor = function(element) {
275     $(element).data('ckeditorInstance').focus();
276   };
277
278   ns.selectall_ckeditor = function(element) {
279     var editor   = $(element).ckeditorGet();
280     var editable = editor.editable();
281     if (editable.is('textarea')) {
282       var textarea = editable.$;
283
284       if (CKEDITOR.env.ie)
285         textarea.createTextRange().execCommand('SelectAll');
286       else {
287         textarea.selectionStart = 0;
288         textarea.selectionEnd   = textarea.value.length;
289       }
290     } else {
291       if (editable.is('body'))
292         editor.document.$.execCommand('SelectAll', false, null);
293
294       else {
295         var range = editor.createRange();
296         range.selectNodeContents(editable);
297         range.select();
298       }
299
300       editor.forceNextSelectionCheck();
301       editor.selectionChange();
302     }
303   }
304
305   ns.init_tabwidget = function(element) {
306     var $element   = $(element);
307     var tabsParams = {};
308     var elementId  = $element.attr('id');
309
310     if (elementId) {
311       var cookieName      = 'jquery_ui_tab_'+ elementId;
312       if (!window.location.hash) {
313         // only activate if there's no hash to overwrite it
314         tabsParams.active   = $.cookie(cookieName);
315       }
316       tabsParams.activate = function(event, ui) {
317         var i = ui.newTab.parent().children().index(ui.newTab);
318         $.cookie(cookieName, i);
319       };
320     }
321
322     $element.tabs(tabsParams);
323   };
324
325   ns.init_text_editor = function(element) {
326     var layouts = {
327       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
328       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
329     };
330
331     var $e      = $(element);
332     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
333     var config  = {
334       entities:      false,
335       language:      'de',
336       removePlugins: 'resize',
337       extraPlugins:  'inline_resize',
338       toolbar:       buttons,
339       disableAutoInline: true,
340       title:         false
341     };
342
343     config.height = $e.height();
344     config.width  = $e.width();
345
346     var editor = CKEDITOR.inline($e.get(0), config);
347     $e.data('ckeditorInstance', editor);
348
349     if ($e.hasClass('texteditor-autofocus'))
350       editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
351   };
352
353   ns.filter_select = function() {
354     var $input  = $(this);
355     var $select = $('#' + $input.data('select-id'));
356     var filter  = $input.val().toLocaleLowerCase();
357
358     $select.find('option').each(function() {
359       if ($(this).text().toLocaleLowerCase().indexOf(filter) != -1)
360         $(this).show();
361       else
362         $(this).hide();
363     });
364   };
365
366   ns.reinit_widgets = function() {
367     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
368       $(elt).datepicker();
369     });
370
371     if (ns.Part) ns.Part.reinit_widgets();
372     if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
373     if (ns.Validator) ns.Validator.reinit_widgets();
374     if (ns.Materialize) ns.Materialize.reinit_widgets();
375
376     if (ns.ProjectPicker)
377       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
378         kivi.ProjectPicker($(elt));
379       });
380
381     if (ns.ChartPicker)
382       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
383         kivi.ChartPicker($(elt));
384       });
385
386     ns.run_once_for('div.filtered_select input', 'filtered_select', function(elt) {
387       $(elt).bind('change keyup', ns.filter_select);
388     });
389
390     var func = kivi.get_function_by_name('local_reinit_widgets');
391     if (func)
392       func();
393
394     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
395       $(elt).tooltipster({
396         contentAsHTML: false,
397         theme: 'tooltipster-light'
398       })
399     });
400
401     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
402       $(elt).tooltipster({
403         contentAsHTML: true,
404         theme: 'tooltipster-light'
405       })
406     });
407
408     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
409     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
410   };
411
412   ns.submit_ajax_form = function(url, form_selector, additional_data) {
413     $(form_selector).ajaxSubmit({
414       url:     url,
415       data:    additional_data,
416       success: ns.eval_json_result
417     });
418
419     return true;
420   };
421
422   // This function submits an existing form given by "form_selector"
423   // and sets the "action" input to "action_to_call" before submitting
424   // it. Any existing input named "action" will be removed prior to
425   // submitting.
426   ns.submit_form_with_action = function(form_selector, action_to_call) {
427     $('[name=action]').remove();
428
429     var $form   = $(form_selector);
430     var $hidden = $('<input type=hidden>');
431
432     $hidden.attr('name',  'action');
433     $hidden.attr('value', action_to_call);
434     $form.append($hidden);
435
436     $form.submit();
437   };
438
439   // This function exists solely so that it can be found with
440   // kivi.get_functions_by_name() and called later on. Using something
441   // like "var func = history["back"]" works, but calling it later
442   // with "func.apply()" doesn't.
443   ns.history_back = function() {
444     history.back();
445   };
446
447   // Return a function object by its name (a string). Works both with
448   // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
449   // "kivi.t8").
450   // Returns null if the object is not found.
451   ns.get_function_by_name = function(name) {
452     var parts = name.match("(.+)\\.([^\\.]+)$");
453     if (!parts)
454       return window[name];
455     return namespace(parts[1])[ parts[2] ];
456   };
457
458   // Open a modal jQuery UI popup dialog. The content can be either
459   // loaded via AJAX (if the parameter 'url' is given) or simply
460   // displayed if it exists in the DOM already (referenced via
461   // 'id') or given via param.html. If an existing DOM div should be used then
462   // the element won't be removed upon closing the dialog which allows
463   // re-opening it later on.
464   //
465   // Parameters:
466   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
467   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
468   // - dialog: an optional object of options passed to the $.dialog() call
469   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
470   ns.popup_dialog = function(params) {
471     if (kivi.Materialize)
472       return kivi.Materialize.popup_dialog(params);
473
474     var dialog;
475
476     params            = params        || { };
477     var id            = params.id     || 'jqueryui_popup_dialog';
478     var custom_close  = params.dialog ? params.dialog.close : undefined;
479     var dialog_params = $.extend(
480       { // kivitendo default parameters:
481           width:  800
482         , height: 500
483         , modal:  true
484       },
485         // User supplied options:
486       params.dialog || { },
487       { // Options that must not be changed:
488         close: function(event, ui) {
489           dialog.dialog('close');
490
491           if (custom_close)
492             custom_close();
493
494           if (params.url || params.html)
495             dialog.remove();
496         }
497       });
498
499     if (!params.url && !params.html) {
500       // Use existing DOM element and show it. No AJAX call.
501       dialog =
502         $('#' + id)
503         .bind('dialogopen', function() {
504           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
505         })
506         .dialog(dialog_params);
507       return true;
508     }
509
510     $('#' + id).remove();
511
512     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
513     dialog.dialog(dialog_params);
514
515     if (params.html) {
516       dialog.html(params.html);
517     } else {
518       // no html? get it via ajax
519       $.ajax({
520         url:     params.url,
521         data:    params.data,
522         type:    params.type,
523         success: function(new_html) {
524           dialog.html(new_html);
525           dialog.removeClass('loading');
526           if (params.load)
527             params.load();
528         }
529       });
530     }
531
532     return true;
533   };
534
535   // Run code only once for each matched element
536   //
537   // This allows running the function 'code' exactly once for each
538   // element that matches 'selector'. This is achieved by storing the
539   // state with jQuery's 'data' function. The 'identification' is
540   // required for differentiating unambiguously so that different code
541   // functions can still be run on the same elements.
542   //
543   // 'code' can be either a function or the name of one. It must
544   // resolve to a function that receives the jQueryfied element as its
545   // sole argument.
546   //
547   // Returns nothing.
548   ns.run_once_for = function(selector, identification, code) {
549     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
550     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
551     if (!fn) {
552       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
553       return;
554     }
555
556     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
557       var $elt = $(elt);
558       $elt.data(attr_name, true);
559       fn($elt);
560     });
561   };
562
563   // Run a function by its name passing it some arguments
564   //
565   // This is a function useful mainly for the ClientJS functionality.
566   // It finds a function by its name and then executes it on an empty
567   // object passing the elements in 'args' (an array) as the function
568   // parameters retuning its result.
569   //
570   // Logs an error to the console and returns 'undefined' if the
571   // function cannot be found.
572   ns.run = function(function_name, args) {
573     var fn = ns.get_function_by_name(function_name);
574     if (fn)
575       return fn.apply({}, args || []);
576
577     console.error('kivi.run("' + function_name + '"): No function by that name found');
578     return undefined;
579   };
580
581   ns.save_file = function(base64_data, content_type, size, attachment_name) {
582     // atob returns a unicode string with one codepoint per octet. revert this
583     const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
584       const byteCharacters = atob(b64Data);
585       const byteArrays = [];
586
587       for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
588         const slice = byteCharacters.slice(offset, offset + sliceSize);
589
590         const byteNumbers = new Array(slice.length);
591         for (let i = 0; i < slice.length; i++) {
592           byteNumbers[i] = slice.charCodeAt(i);
593         }
594
595         const byteArray = new Uint8Array(byteNumbers);
596         byteArrays.push(byteArray);
597       }
598
599       const blob = new Blob(byteArrays, {type: contentType});
600       return blob;
601     }
602
603     var blob = b64toBlob(base64_data, content_type);
604     var a = $("<a style='display: none;'/>");
605     var url = window.URL.createObjectURL(blob);
606     a.attr("href", url);
607     a.attr("download", attachment_name);
608     $("body").append(a);
609     a[0].click();
610     window.URL.revokeObjectURL(url);
611     a.remove();
612   }
613
614   ns.detect_duplicate_ids_in_dom = function() {
615     var ids   = {},
616         found = false;
617
618     $('[id]').each(function() {
619       if (this.id && ids[this.id]) {
620         found = true;
621         console.warn('Duplicate ID #' + this.id);
622       }
623       ids[this.id] = 1;
624     });
625
626     if (!found)
627       console.log('No duplicate IDs found :)');
628   };
629
630   ns.validate_form = function(selector) {
631     if (!kivi.Validator) {
632       console.log('kivi.Validator is not loaded');
633     } else {
634       return kivi.Validator.validate_all(selector);
635     }
636   };
637
638   // Verifies that at least one checkbox matching the
639   // "checkbox_selector" is actually checked. If not, an error message
640   // is shown, and false is returned. Otherwise (at least one of them
641   // is checked) nothing is shown and true returned.
642   //
643   // Can be used in checks when clicking buttons.
644   ns.check_if_entries_selected = function(checkbox_selector) {
645     if ($(checkbox_selector + ':checked').length > 0)
646       return true;
647
648     alert(kivi.t8('No entries have been selected.'));
649
650     return false;
651   };
652
653   ns.switch_areainput_to_textarea = function(id) {
654     var $input = $('#' + id);
655     if (!$input.length)
656       return;
657
658     var $area = $('<textarea></textarea>');
659
660     $area.prop('rows', 3);
661     $area.prop('cols', $input.prop('size') || 40);
662     $area.prop('name', $input.prop('name'));
663     $area.prop('id',   $input.prop('id'));
664     $area.val($input.val());
665
666     $input.parent().replaceWith($area);
667     $area.focus();
668   };
669
670   ns.set_cursor_position = function(selector, position) {
671     var $input = $(selector);
672     if (position === 'end')
673       position = $input.val().length;
674
675     $input.prop('selectionStart', position);
676     $input.prop('selectionEnd',   position);
677   };
678 });
679
680 kivi = namespace('kivi');