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