kivi.Part.js: keydown ausgelagert in eigenen handler
[kivitendo-erp.git] / js / kivi.Part.js
1 namespace('kivi.Part', function(ns) {
2   'use strict';
3
4   ns.open_history_popup = function() {
5     var id = $("#part_id").val();
6     kivi.popup_dialog({
7       url:    'controller.pl?action=Part/history&part.id=' + id,
8       dialog: { title: kivi.t8('History') },
9     });
10   }
11
12   ns.save = function() {
13     var data = $('#ic').serializeArray();
14     data.push({ name: 'action', value: 'Part/save' });
15
16     $.post("controller.pl", data, kivi.eval_json_result);
17   };
18
19   ns.use_as_new = function() {
20     var oldid = $("#part_id").val();
21     $('#ic').attr('action', 'controller.pl?action=Part/use_as_new&old_id=' + oldid);
22     $('#ic').submit();
23   };
24
25   ns.delete = function() {
26     var data = $('#ic').serializeArray();
27     data.push({ name: 'action', value: 'Part/delete' });
28
29     $.post("controller.pl", data, kivi.eval_json_result);
30   };
31
32   ns.reformat_number = function(event) {
33     $(event.target).val(kivi.format_amount(kivi.parse_amount($(event.target).val()), -2));
34   };
35
36   ns.set_tab_active_by_index = function (index) {
37     $("#ic_tabs").tabs({active: index})
38   };
39
40   ns.set_tab_active_by_name= function (name) {
41     var index = $('#ic_tabs a[href=#' + name + ']').parent().index();
42     ns.set_tab_active_by_index(index);
43   };
44
45   ns.reorder_items = function(order_by) {
46     var dir = $('#' + order_by + '_header_id a img').attr("data-sort-dir");
47     var part_type = $("#part_part_type").val();
48
49     var data;
50     if (part_type === 'assortment') {
51       $('#assortment thead a img').remove();
52       data = $('#assortment :input').serializeArray();
53     } else if ( part_type === 'assembly') {
54       $('#assembly thead a img').remove();
55       data = $('#assembly :input').serializeArray();
56     }
57
58     var src;
59     if (dir == "1") {
60       dir = "0";
61       src = "image/up.png";
62     } else {
63       dir = "1";
64       src = "image/down.png";
65     }
66
67     $('#' + order_by + '_header_id a').append('<img border=0 data-sort-dir=' + dir + ' src=' + src + ' alt="' + kivi.t8('sort items') + '">');
68
69     data.push({ name: 'action',    value: 'Part/reorder_items' },
70               { name: 'order_by',  value: order_by             },
71               { name: 'part_type', value: part_type            },
72               { name: 'sort_dir',  value: dir                  });
73
74     $.post("controller.pl", data, kivi.eval_json_result);
75   };
76
77   ns.assortment_recalc = function() {
78     var data = $('#assortment :input').serializeArray();
79     data.push({ name: 'action', value: 'Part/update_item_totals' },
80               { name: 'part_type', value: 'assortment'                   });
81
82     $.post("controller.pl", data, kivi.eval_json_result);
83   };
84
85   ns.assembly_recalc = function() {
86     var data = $('#assembly :input').serializeArray();
87     data.push( { name: 'action',    value: 'Part/update_item_totals' },
88                { name: 'part_type', value: 'assembly'                        });
89
90     $.post("controller.pl", data, kivi.eval_json_result);
91   };
92
93   ns.set_assortment_sellprice = function() {
94     $("#part_sellprice_as_number").val($("#items_sellprice_sum").html());
95     // ns.set_tab_active_by_name('basic_data');
96     // $("#part_sellprice_as_number").focus();
97   };
98
99   ns.set_assortment_lsg_sellprice = function() {
100     $("#items_lsg_sellprice_sum_basic").closest('td').find('input').val($("#items_lsg_sellprice_sum").html());
101   };
102
103   ns.set_assortment_douglas_sellprice = function() {
104     $("#items_douglas_sellprice_sum_basic").closest('td').find('input').val($("#items_douglas_sellprice_sum").html());
105   };
106
107   ns.set_assortment_lastcost = function() {
108     $("#part_lastcost_as_number").val($("#items_lastcost_sum").html());
109     // ns.set_tab_active_by_name('basic_data');
110     // $("#part_lastcost_as_number").focus();
111   };
112
113   ns.set_assembly_sellprice = function() {
114     $("#part_sellprice_as_number").val($("#items_sellprice_sum").html());
115     // ns.set_tab_active_by_name('basic_data');
116     // $("#part_sellprice_as_number").focus();
117   };
118
119   ns.renumber_positions = function() {
120     var part_type = $("#part_part_type").val();
121     var rows;
122     if (part_type === 'assortment') {
123       rows = $('.assortment_item_row [name="position"]');
124     } else if ( part_type === 'assembly') {
125       rows = $('.assembly_item_row [name="position"]');
126     }
127     $(rows).each(function(idx, elt) {
128       $(elt).html(idx+1);
129       var row = $(elt).closest('tr');
130       if ( idx % 2 === 0 ) {
131         if ( row.hasClass('listrow1') ) {
132           row.removeClass('listrow1');
133           row.addClass('listrow0');
134         }
135       } else {
136         if ( row.hasClass('listrow0') ) {
137           row.removeClass('listrow0');
138           row.addClass('listrow1');
139         }
140       }
141     });
142   };
143
144   ns.delete_item_row = function(clicked) {
145     var row = $(clicked).closest('tr');
146     $(row).remove();
147     var part_type = $("#part_part_type").val();
148     ns.renumber_positions();
149     if (part_type === 'assortment') {
150       ns.assortment_recalc();
151     } else if ( part_type === 'assembly') {
152       ns.assembly_recalc();
153     }
154   };
155
156   ns.add_assortment_item = function() {
157     if ($('#add_assortment_item_id').val() === '') return;
158
159     $('#row_table_id thead a img').remove();
160
161     var data = $('#assortment :input').serializeArray();
162     data.push({ name: 'action', value: 'Part/add_assortment_item' },
163               { name: 'part.id', value: $('#part_id').val()       },
164               { name: 'part.part_type', value: 'assortment'       });
165
166     $.post("controller.pl", data, kivi.eval_json_result);
167   };
168
169   ns.add_assembly_item = function() {
170     if ($('#add_assembly_item_id').val() === '') return;
171
172     var data = $('#assembly :input').serializeArray();
173     data.push({ name: 'action', value: 'Part/add_assembly_item' },
174               { name: 'part.id', value: $("#part_id").val()     },
175               { name: 'part.part_type', value: 'assortment'     });
176
177     $.post("controller.pl", data, kivi.eval_json_result);
178   };
179
180   ns.redisplay_items = function(data) {
181     var old_rows;
182     var part_type = $("#part_part_type").val();
183     if (part_type === 'assortment') {
184       old_rows = $('.assortment_item_row').detach();
185     } else if ( part_type === 'assembly') {
186       old_rows = $('.assembly_item_row').detach();
187     }
188     var new_rows = [];
189     $(data).each(function(idx, elt) {
190       new_rows.push(old_rows[elt.old_pos - 1]);
191     });
192     if (part_type === 'assortment') {
193       $(new_rows).appendTo($('#assortment_items'));
194     } else if ( part_type === 'assembly') {
195       $(new_rows).appendTo($('#assembly_items'));
196     }
197     ns.renumber_positions();
198   };
199
200   ns.focus_last_assortment_input = function () {
201     $("#assortment_items tr:last").find('input[type=text]').filter(':visible:first').focus();
202   };
203
204   ns.focus_last_assembly_input = function () {
205     $("#assembly_rows tr:last").find('input[type=text]').filter(':visible:first').focus();
206   };
207
208   ns.show_multi_items_dialog = function(part_type,part_id) {
209
210     $('#row_table_id thead a img').remove();
211
212     kivi.popup_dialog({
213       url: 'controller.pl?action=Part/show_multi_items_dialog',
214       data: { callback:         'Part/add_multi_' + part_type + '_items',
215               callback_data_id: 'ic',
216               'part.part_type': part_type,
217               'part.id'       : part_id,
218             },
219       id: 'jq_multi_items_dialog',
220       dialog: {
221         title: kivi.t8('Add multiple items'),
222         width:  800,
223         height: 800
224       }
225     });
226     return true;
227   };
228
229   ns.close_multi_items_dialog = function() {
230     $('#jq_multi_items_dialog').dialog('close');
231   };
232
233
234   // makemodel
235   ns.makemodel_renumber_positions = function() {
236     $('.makemodel_row [name="position"]').each(function(idx, elt) {
237       $(elt).html(idx+1);
238     });
239   };
240
241   ns.delete_makemodel_row = function(clicked) {
242     var row = $(clicked).closest('tr');
243     $(row).remove();
244
245     ns.makemodel_renumber_positions();
246   };
247
248   ns.add_makemodel_row = function() {
249     if ($('#add_makemodelid').val() === '') return;
250
251     var data = $('#makemodel_table :input').serializeArray();
252     data.push({ name: 'action', value: 'Part/add_makemodel_row' });
253
254     $.post("controller.pl", data, kivi.eval_json_result);
255   };
256
257   ns.focus_last_makemodel_input = function () {
258     $("#makemodel_rows tr:last").find('input[type=text]').filter(':visible:first').focus();
259   };
260
261
262   ns.reload_bin_selection = function() {
263     $.post("controller.pl", { action: 'Part/warehouse_changed', warehouse_id: function(){ return $('#part_warehouse_id').val() } },   kivi.eval_json_result);
264   }
265
266   var KEY = {
267     TAB:       9,
268     ENTER:     13,
269     SHIFT:     16,
270     CTRL:      17,
271     ALT:       18,
272     ESCAPE:    27,
273     PAGE_UP:   33,
274     PAGE_DOWN: 34,
275     LEFT:      37,
276     UP:        38,
277     RIGHT:     39,
278     DOWN:      40,
279   };
280
281   ns.Picker = function($real, options) {
282     var self = this;
283     this.o = $.extend({
284       limit: 20,
285       delay: 50,
286       fat_set_item: $real.hasClass(this.CLASSES.FAT_SET_ITEM),
287       action: {
288         on_enter_match_none: function(){ },
289         on_enter_match_one:  function(){ $('#update_button').click(); },
290         on_enter_match_many: function(){ self.open_dialog(); }
291       }
292     }, options);
293     this.$real              = $real;
294     this.real_id            = $real.attr('id');
295     this.last_real          = $real.val();
296     this.$dummy             = $('#' + this.real_id + '_name');
297     this.$part_type         = $('#' + this.real_id + '_part_type');
298     this.$classification_id = $('#' + this.real_id + '_classification_id');
299     this.$unit              = $('#' + this.real_id + '_unit');
300     this.$convertible_unit  = $('#' + this.real_id + '_convertible_unit');
301     this.autocomplete_open  = false;
302     this.state              = this.STATES.PICKED;
303     this.last_dummy         = this.$dummy.val();
304     this.timer              = undefined;
305
306     this.init();
307   };
308
309   ns.Picker.prototype = {
310     CLASSES: {
311       PICKED:       'partpicker-picked',
312       UNDEFINED:    'partpicker-undefined',
313       FAT_SET_ITEM: 'partpicker_fat_set_item',
314     },
315     ajax_data: function(term) {
316       var data = {
317         'filter.all:substr:multi::ilike': term,
318         'filter.obsolete': 0,
319         'filter.unit_obj.convertible_to': this.$convertible_unit && this.$convertible_unit.val() ? this.$convertible_unit.val() : '',
320         current:  this.$real.val(),
321       };
322
323       if (this.$part_type && this.$part_type.val())
324         data['filter.part_type'] = this.$part_type.val().split(',');
325
326       if (this.$classification_id && this.$classification_id.val())
327         data['filter.classification_id'] = this.$classification_id.val().split(',');
328
329       if (this.$unit && this.$unit.val())
330         data['filter.unit'] = this.$unit.val().split(',');
331
332       return data;
333     },
334     set_item: function(item) {
335       var self = this;
336       if (item.id) {
337         this.$real.val(item.id);
338         // autocomplete ui has name, use the value for ajax items, which contains displayable_name
339         this.$dummy.val(item.name ? item.name : item.value);
340       } else {
341         this.$real.val('');
342         this.$dummy.val('');
343       }
344       this.state      = this.STATES.PICKED;
345       this.last_real  = this.$real.val();
346       this.last_dummy = this.$dummy.val();
347       this.$real.trigger('change');
348
349       if (this.o.fat_set_item && item.id) {
350         $.ajax({
351           url: 'controller.pl?action=Part/show.json',
352           data: { 'part.id': item.id },
353           success: function(rsp) {
354             self.$real.trigger('set_item:PartPicker', rsp);
355           },
356         });
357       } else {
358         this.$real.trigger('set_item:PartPicker', item);
359       }
360       this.annotate_state();
361     },
362     make_defined_state: function() {
363       if (this.state == this.STATES.PICKED) {
364         this.annotate_state();
365         return true
366       } else if (this.state == this.STATES.UNDEFINED && this.$dummy.val() === '')
367         this.set_item({})
368       else {
369         this.set_item({ id: this.last_real, name: this.last_dummy })
370       }
371       this.annotate_state();
372     },
373     annotate_state: function() {
374       if (this.state == this.STATES.PICKED)
375         this.$dummy.removeClass(this.STATES.UNDEFINED).addClass(this.STATES.PICKED);
376       else if (this.state == this.STATES.UNDEFINED && this.$dummy.val() === '')
377         this.$dummy.removeClass(this.STATES.UNDEFINED).addClass(this.STATES.PICKED);
378       else {
379         this.$dummy.addClass(this.STATES.UNDEFINED).removeClass(this.STATES.PICKED);
380       }
381     },
382     handle_changed_text: function(callbacks) {
383       var self = this;
384       $.ajax({
385         url: 'controller.pl?action=Part/ajax_autocomplete',
386         dataType: "json",
387         data: $.extend( self.ajax_data(self.$dummy.val()), { prefer_exact: 1 } ),
388         success: function (data) {
389           if (data.length == 1) {
390             self.set_item(data[0]);
391             if (callbacks && callbacks.match_one) callbacks.match_one(data[0]);
392           } else if (data.length > 1) {
393             self.state = self.STATES.UNDEFINED;
394             if (callbacks && callbacks.match_many) callbacks.match_many(data);
395           } else {
396             self.state = self.STATES.UNDEFINED;
397             if (callbacks && callbacks.match_none) callbacks.match_none();
398           }
399           self.annotate_state();
400         }
401       });
402     },
403     /*  In case users are impatient and want to skip ahead:
404      *  Capture <enter> key events and check if it's a unique hit.
405      *  If it is, go ahead and assume it was selected. If it wasn't don't do
406      *  anything so that autocompletion kicks in.  For <tab> don't prevent
407      *  propagation. It would be nice to catch it, but javascript is too stupid
408      *  to fire a tab event later on, so we'd have to reimplement the "find
409      *  next active element in tabindex order and focus it".
410      */
411     /* note:
412      *  event.which does not contain tab events in keypressed in firefox but will report 0
413      *  chrome does not fire keypressed at all on tab or escape
414      */
415     handle_keydown: function(event) {
416       var self = this;
417       if (event.which == KEY.ENTER || event.which == KEY.TAB) {
418         // if string is empty assume they want to delete
419         if (self.$dummy.val() === '') {
420           self.set_item({});
421           return true;
422         } else if (self.state == self.STATES.PICKED) {
423           return true;
424         }
425         if (event.which == KEY.TAB) {
426           event.preventDefault();
427           self.handle_changed_text();
428         }
429         if (event.which == KEY.ENTER) {
430           self.handle_changed_text({
431             match_one:  self.o.action.on_enter_match_one,
432             match_many: self.o.action.on_enter_match_many
433           });
434           return false;
435         }
436       } else if (event.which == KEY.DOWN && !self.autocomplete_open) {
437         var old_options = self.$dummy.autocomplete('option');
438         self.$dummy.autocomplete('option', 'minLength', 0);
439         self.$dummy.autocomplete('search', self.$dummy.val());
440         self.$dummy.autocomplete('option', 'minLength', old_options.minLength);
441       } else if ((event.which != KEY.SHIFT) && (event.which != KEY.CTRL) && (event.which != KEY.ALT)) {
442         self.state = self.STATES.UNDEFINED;
443       }
444     },
445     open_dialog: function() {
446       new ns.PickerPopup(this);
447     },
448     init: function() {
449       var self = this;
450       this.$dummy.autocomplete({
451         source: function(req, rsp) {
452           $.ajax($.extend(self.o, {
453             url:      'controller.pl?action=Part/ajax_autocomplete',
454             dataType: "json",
455             data:     self.ajax_data(req.term),
456             success:  function (data){ rsp(data) }
457           }));
458         },
459         select: function(event, ui) {
460           self.set_item(ui.item);
461         },
462         search: function(event, ui) {
463           if ((event.which == KEY.SHIFT) || (event.which == KEY.CTRL) || (event.which == KEY.ALT))
464             event.preventDefault();
465         },
466         open: function() {
467           self.autocomplete_open = true;
468         },
469         close: function() {
470           self.autocomplete_open = false;
471         }
472       });
473       this.$dummy.keydown(function(event){ self.handle_keydown(event) });
474       this.$dummy.on('paste', function(){
475         setTimeout(function() {
476           self.handle_changed_text();
477         }, 1);
478       });
479       this.$dummy.blur(function(){
480         window.clearTimeout(self.timer);
481         self.timer = window.setTimeout(function() { self.annotate_state() }, 100);
482       });
483
484       var popup_button = $('<span>').addClass('ppp_popup_button');
485       this.$dummy.after(popup_button);
486       popup_button.click(function() { self.open_dialog() });
487     }
488   };
489   ns.Picker.prototype.STATES = {
490     PICKED:    ns.Picker.prototype.CLASSES.PICKED,
491     UNDEFINED: ns.Picker.prototype.CLASSES.UNDEFINED
492   };
493
494   ns.PickerPopup = function(pp) {
495     this.timer = undefined;
496     this.pp    = pp;
497     this.open_dialog();
498   };
499
500   ns.PickerPopup.prototype = {
501     open_dialog: function() {
502       var self = this;
503       kivi.popup_dialog({
504         url: 'controller.pl?action=Part/part_picker_search',
505         data: $.extend({
506           real_id: self.pp.real_id,
507         }, self.pp.ajax_data(this.pp.$dummy.val())),
508         id: 'part_selection',
509         dialog: {
510           title: kivi.t8('Part picker'),
511           width: 800,
512           height: 800,
513         },
514         load: function() { self.init_search(); }
515       });
516       window.clearTimeout(this.timer);
517       return true;
518     },
519     init_search: function() {
520       var self = this;
521       $('#part_picker_filter').keypress(function(e) { self.result_timer(e) }).focus();
522       $('#no_paginate').change(function() { self.update_results() });
523       this.update_results();
524     },
525     update_results: function() {
526       var self = this;
527       $.ajax({
528         url: 'controller.pl?action=Part/part_picker_result',
529         data: $.extend({
530          'real_id':    self.pp.$real.val(),
531           no_paginate: $('#no_paginate').prop('checked') ? 1 : 0,
532         }, self.pp.ajax_data(function(){
533           var val = $('#part_picker_filter').val();
534           return val === undefined ? '' : val
535         })),
536         success: function(data){
537           $('#part_picker_result').html(data);
538           self.init_results();
539         }
540       });
541     },
542     init_results: function() {
543       var self = this;
544       $('div.part_picker_part').each(function(){
545         $(this).click(function(){
546           self.pp.set_item({
547             id:   $(this).children('input.part_picker_id').val(),
548             name: $(this).children('input.part_picker_description').val(),
549             classification_id: $(this).children('input.part_picker_classification_id').val(),
550             unit: $(this).children('input.part_picker_unit').val(),
551             partnumber:  $(this).children('input.part_picker_partnumber').val(),
552             description: $(this).children('input.part_picker_description').val(),
553           });
554           self.close_popup();
555           self.pp.$dummy.focus();
556           return true;
557         });
558       });
559       $('#part_selection').keydown(function(e){
560          if (e.which == KEY.ESCAPE) {
561            self.close_popup();
562            self.pp.$dummy.focus();
563          }
564       });
565     },
566     result_timer: function(event) {
567       var self = this;
568       if (!$('no_paginate').prop('checked')) {
569         if (event.keyCode == KEY.PAGE_UP) {
570           $('#part_picker_result a.paginate-prev').click();
571           return;
572         }
573         if (event.keyCode == KEY.PAGE_DOWN) {
574           $('#part_picker_result a.paginate-next').click();
575           return;
576         }
577       }
578       window.clearTimeout(this.timer);
579       if (event.which == KEY.ENTER) {
580         self.update_results();
581       } else {
582         this.timer = window.setTimeout(function() { self.update_results() }, 100);
583       }
584     },
585     close_popup: function() {
586       $('#part_selection').dialog('close');
587     }
588   };
589
590   ns.reinit_widgets = function() {
591     kivi.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
592       if (!$(elt).data('part_picker'))
593         $(elt).data('part_picker', new kivi.Part.Picker($(elt)));
594     });
595   }
596
597   ns.init = function() {
598     ns.reinit_widgets();
599   }
600
601   $(function(){
602
603     // assortment
604     // TODO: allow units for assortment items
605     $('#add_assortment_item_id').on('set_item:PartPicker', function(e,o) { $('#add_item_unit').val(o.unit) });
606
607     $('#ic').on('focusout', '.reformat_number', function(event) {
608        ns.reformat_number(event);
609     })
610
611     $('.add_assortment_item_input').keydown(function(event) {
612       if(event.keyCode == 13) {
613         event.preventDefault();
614         if ($("input[name='add_items[+].parts_id']").val() !== '' ) {
615           kivi.Part.show_multi_items_dialog("assortment");
616          // ns.add_assortment_item();
617         }
618         return false;
619       }
620     });
621
622     $('.add_assembly_item_input').keydown(function(event) {
623       if(event.keyCode == 13) {
624         event.preventDefault();
625         if ($("input[name='add_items[+].parts_id']").val() !== '' ) {
626           kivi.Part.show_multi_items_dialog("assortment");
627           // ns.add_assembly_item();
628         }
629         return false;
630       }
631     });
632
633     $('.add_makemodel_input').keydown(function(event) {
634       if(event.keyCode == 13) {
635         event.preventDefault();
636         ns.add_makemodel_row();
637         return false;
638       }
639     });
640
641     $('#part_warehouse_id').change(kivi.Part.reload_bin_selection);
642
643     ns.init();
644   });
645 });