epic-s6ts
[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       disableNativeSpellChecker: false
342     };
343
344     config.height = $e.height();
345     config.width  = $e.width();
346
347     var editor = CKEDITOR.inline($e.get(0), config);
348     $e.data('ckeditorInstance', editor);
349
350     if ($e.hasClass('texteditor-space-for-toolbar'))
351       editor.on('instanceReady', function() {
352         var editor   = $e.ckeditorGet();
353         var editable = editor.editable();
354         $(editable.$).css("margin-top", "30px");
355       });
356
357
358     if ($e.hasClass('texteditor-autofocus'))
359       editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
360   };
361
362   ns.filter_select = function() {
363     var $input  = $(this);
364     var $select = $('#' + $input.data('select-id'));
365     var filter  = $input.val().toLocaleLowerCase();
366
367     $select.find('option').each(function() {
368       if ($(this).text().toLocaleLowerCase().indexOf(filter) != -1)
369         $(this).show();
370       else
371         $(this).hide();
372     });
373   };
374
375   ns.reinit_widgets = function() {
376     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
377       $(elt).datepicker();
378     });
379
380     if (ns.Part) ns.Part.reinit_widgets();
381     if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
382     if (ns.Validator) ns.Validator.reinit_widgets();
383     if (ns.Materialize) ns.Materialize.reinit_widgets();
384
385     if (ns.ProjectPicker)
386       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
387         kivi.ProjectPicker($(elt));
388       });
389
390     if (ns.ChartPicker)
391       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
392         kivi.ChartPicker($(elt));
393       });
394
395     ns.run_once_for('div.filtered_select input', 'filtered_select', function(elt) {
396       $(elt).bind('change keyup', ns.filter_select);
397     });
398
399     var func = kivi.get_function_by_name('local_reinit_widgets');
400     if (func)
401       func();
402
403     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
404       $(elt).tooltipster({
405         contentAsHTML: false,
406         theme: 'tooltipster-light'
407       })
408     });
409
410     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
411       $(elt).tooltipster({
412         contentAsHTML: true,
413         theme: 'tooltipster-light'
414       })
415     });
416
417     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
418     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
419   };
420
421   ns.submit_ajax_form = function(url, form_selector, additional_data) {
422     $(form_selector).ajaxSubmit({
423       url:     url,
424       data:    additional_data,
425       success: ns.eval_json_result
426     });
427
428     return true;
429   };
430
431   // This function submits an existing form given by "form_selector"
432   // and sets the "action" input to "action_to_call" before submitting
433   // it. Any existing input named "action" will be removed prior to
434   // submitting.
435   ns.submit_form_with_action = function(form_selector, action_to_call) {
436     $('[name=action]').remove();
437
438     var $form   = $(form_selector);
439     var $hidden = $('<input type=hidden>');
440
441     $hidden.attr('name',  'action');
442     $hidden.attr('value', action_to_call);
443     $form.append($hidden);
444
445     $form.submit();
446   };
447
448   // This function exists solely so that it can be found with
449   // kivi.get_functions_by_name() and called later on. Using something
450   // like "var func = history["back"]" works, but calling it later
451   // with "func.apply()" doesn't.
452   ns.history_back = function() {
453     history.back();
454   };
455
456   // Return a function object by its name (a string). Works both with
457   // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
458   // "kivi.t8").
459   // Returns null if the object is not found.
460   ns.get_function_by_name = function(name) {
461     var parts = name.match("(.+)\\.([^\\.]+)$");
462     if (!parts)
463       return window[name];
464     return namespace(parts[1])[ parts[2] ];
465   };
466
467   // Open a modal jQuery UI popup dialog. The content can be either
468   // loaded via AJAX (if the parameter 'url' is given) or simply
469   // displayed if it exists in the DOM already (referenced via
470   // 'id') or given via param.html. If an existing DOM div should be used then
471   // the element won't be removed upon closing the dialog which allows
472   // re-opening it later on.
473   //
474   // Parameters:
475   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
476   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
477   // - dialog: an optional object of options passed to the $.dialog() call
478   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
479   ns.popup_dialog = function(params) {
480     if (kivi.Materialize)
481       return kivi.Materialize.popup_dialog(params);
482
483     var dialog;
484
485     params            = params        || { };
486     var id            = params.id     || 'jqueryui_popup_dialog';
487     var custom_close  = params.dialog ? params.dialog.close : undefined;
488     var dialog_params = $.extend(
489       { // kivitendo default parameters:
490           width:  800
491         , height: 500
492         , modal:  true
493       },
494         // User supplied options:
495       params.dialog || { },
496       { // Options that must not be changed:
497         close: function(event, ui) {
498           dialog.dialog('close');
499
500           if (custom_close)
501             custom_close();
502
503           if (params.url || params.html)
504             dialog.remove();
505         }
506       });
507
508     if (!params.url && !params.html) {
509       // Use existing DOM element and show it. No AJAX call.
510       dialog =
511         $('#' + id)
512         .bind('dialogopen', function() {
513           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
514         })
515         .dialog(dialog_params);
516       return true;
517     }
518
519     $('#' + id).remove();
520
521     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
522     dialog.dialog(dialog_params);
523
524     if (params.html) {
525       dialog.html(params.html);
526     } else {
527       // no html? get it via ajax
528       $.ajax({
529         url:     params.url,
530         data:    params.data,
531         type:    params.type,
532         success: function(new_html) {
533           dialog.html(new_html);
534           dialog.removeClass('loading');
535           if (params.load)
536             params.load();
537         }
538       });
539     }
540
541     return true;
542   };
543
544   // Run code only once for each matched element
545   //
546   // This allows running the function 'code' exactly once for each
547   // element that matches 'selector'. This is achieved by storing the
548   // state with jQuery's 'data' function. The 'identification' is
549   // required for differentiating unambiguously so that different code
550   // functions can still be run on the same elements.
551   //
552   // 'code' can be either a function or the name of one. It must
553   // resolve to a function that receives the jQueryfied element as its
554   // sole argument.
555   //
556   // Returns nothing.
557   ns.run_once_for = function(selector, identification, code) {
558     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
559     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
560     if (!fn) {
561       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
562       return;
563     }
564
565     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
566       var $elt = $(elt);
567       $elt.data(attr_name, true);
568       fn($elt);
569     });
570   };
571
572   // Run a function by its name passing it some arguments
573   //
574   // This is a function useful mainly for the ClientJS functionality.
575   // It finds a function by its name and then executes it on an empty
576   // object passing the elements in 'args' (an array) as the function
577   // parameters retuning its result.
578   //
579   // Logs an error to the console and returns 'undefined' if the
580   // function cannot be found.
581   ns.run = function(function_name, args) {
582     var fn = ns.get_function_by_name(function_name);
583     if (fn)
584       return fn.apply({}, args || []);
585
586     console.error('kivi.run("' + function_name + '"): No function by that name found');
587     return undefined;
588   };
589
590   ns.save_file = function(base64_data, content_type, size, attachment_name) {
591     // atob returns a unicode string with one codepoint per octet. revert this
592     const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
593       const byteCharacters = atob(b64Data);
594       const byteArrays = [];
595
596       for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
597         const slice = byteCharacters.slice(offset, offset + sliceSize);
598
599         const byteNumbers = new Array(slice.length);
600         for (let i = 0; i < slice.length; i++) {
601           byteNumbers[i] = slice.charCodeAt(i);
602         }
603
604         const byteArray = new Uint8Array(byteNumbers);
605         byteArrays.push(byteArray);
606       }
607
608       const blob = new Blob(byteArrays, {type: contentType});
609       return blob;
610     }
611
612     var blob = b64toBlob(base64_data, content_type);
613     var a = $("<a style='display: none;'/>");
614     var url = window.URL.createObjectURL(blob);
615     a.attr("href", url);
616     a.attr("download", attachment_name);
617     $("body").append(a);
618     a[0].click();
619     window.URL.revokeObjectURL(url);
620     a.remove();
621   }
622
623   ns.detect_duplicate_ids_in_dom = function() {
624     var ids   = {},
625         found = false;
626
627     $('[id]').each(function() {
628       if (this.id && ids[this.id]) {
629         found = true;
630         console.warn('Duplicate ID #' + this.id);
631       }
632       ids[this.id] = 1;
633     });
634
635     if (!found)
636       console.log('No duplicate IDs found :)');
637   };
638
639   ns.validate_form = function(selector) {
640     if (!kivi.Validator) {
641       console.log('kivi.Validator is not loaded');
642     } else {
643       return kivi.Validator.validate_all(selector);
644     }
645   };
646
647   // Verifies that at least one checkbox matching the
648   // "checkbox_selector" is actually checked. If not, an error message
649   // is shown, and false is returned. Otherwise (at least one of them
650   // is checked) nothing is shown and true returned.
651   //
652   // Can be used in checks when clicking buttons.
653   ns.check_if_entries_selected = function(checkbox_selector) {
654     if ($(checkbox_selector + ':checked').length > 0)
655       return true;
656
657     alert(kivi.t8('No entries have been selected.'));
658
659     return false;
660   };
661
662   ns.switch_areainput_to_textarea = function(id) {
663     var $input = $('#' + id);
664     if (!$input.length)
665       return;
666
667     var $area = $('<textarea></textarea>');
668
669     $area.prop('rows', 3);
670     $area.prop('cols', $input.prop('size') || 40);
671     $area.prop('name', $input.prop('name'));
672     $area.prop('id',   $input.prop('id'));
673     $area.val($input.val());
674
675     $input.parent().replaceWith($area);
676     $area.focus();
677   };
678
679   ns.set_cursor_position = function(selector, position) {
680     var $input = $(selector);
681     if (position === 'end')
682       position = $input.val().length;
683
684     $input.prop('selectionStart', position);
685     $input.prop('selectionEnd',   position);
686   };
687
688   ns._shell_escape = function(str) {
689     if (str.match(/^[a-zA-Z0-9.,_=+/-]+$/))
690       return str;
691
692     return "'" + str.replace(/'/, "'\\''") + "'";
693   };
694
695   ns.call_as_curl = function(params) {
696     params      = params || {};
697     var uri     = document.documentURI.replace(/\?.*/, '');
698     var command = ['curl', '--user', kivi.myconfig.login + ':SECRET', '--request', params.method || 'POST']
699
700     $(params.data || []).each(function(idx, elt) {
701       command = command.concat([ '--form-string', elt.name + '=' + (elt.value || '') ]);
702     });
703
704     command.push(uri);
705
706     return $.map(command, function(elt, idx) {
707       return kivi._shell_escape(elt);
708     }).join(' ');
709   };
710
711   ns.serialize = function(source, target = [], prefix, in_array = false) {
712     let arr_prefix = first => in_array ? (first ? "[+]" : "[]") : "";
713
714     if (Array.isArray(source) ) {
715       source.forEach(( val, i ) => {
716         ns.serialize(val, target, prefix + arr_prefix(i == 0), true);
717       });
718     } else if (typeof source === "object") {
719       let first = true;
720       for (let key in source) {
721         ns.serialize(source[key], target, (prefix !== undefined ? prefix + arr_prefix(first) + "." : "") + key);
722         first = false;
723       }
724     } else {
725       target.push({ name: prefix + arr_prefix(false), value: source });
726     }
727
728     return target;
729   };
730 });
731
732 kivi = namespace('kivi');