kivi.Part.js: Datenübergabe Picker<->Presenter auf data umgestellt
[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       action: {
287         on_enter_match_none: function(){ },
288         on_enter_match_one:  function(){ $('#update_button').click(); },
289         on_enter_match_many: function(){ self.open_dialog(); }
290       }
291     }, $real.data('part-picker-data'), options);
292     this.$real              = $real;
293     this.real_id            = $real.attr('id');
294     this.last_real          = $real.val();
295     this.$dummy             = $($real.siblings()[0]);
296     this.autocomplete_open  = false;
297     this.state              = this.STATES.PICKED;
298     this.last_dummy         = this.$dummy.val();
299     this.timer              = undefined;
300
301     this.init();
302   };
303
304   ns.Picker.prototype = {
305     CLASSES: {
306       PICKED:       'partpicker-picked',
307       UNDEFINED:    'partpicker-undefined',
308     },
309     ajax_data: function(term) {
310       var data = {
311         'filter.all:substr:multi::ilike': term,
312         'filter.obsolete': 0,
313         current:  this.$real.val(),
314       };
315
316       if (this.o.part_type)
317         data['filter.part_type'] = this.o.part_type.split(',');
318
319       if (this.o.classification_id)
320         data['filter.classification_id'] = this.o.classification_id.split(',');
321
322       if (this.o.unit)
323         data['filter.unit'] = this.o.unit.split(',');
324
325       if (this.o.convertible_unit)
326         data['filter.unit_obj.convertible_to'] = this.o.convertible_unit;
327
328       return data;
329     },
330     set_item: function(item) {
331       var self = this;
332       if (item.id) {
333         this.$real.val(item.id);
334         // autocomplete ui has name, use the value for ajax items, which contains displayable_name
335         this.$dummy.val(item.name ? item.name : item.value);
336       } else {
337         this.$real.val('');
338         this.$dummy.val('');
339       }
340       this.state      = this.STATES.PICKED;
341       this.last_real  = this.$real.val();
342       this.last_dummy = this.$dummy.val();
343       this.$real.trigger('change');
344
345       if (this.o.fat_set_item && item.id) {
346         $.ajax({
347           url: 'controller.pl?action=Part/show.json',
348           data: { 'part.id': item.id },
349           success: function(rsp) {
350             self.$real.trigger('set_item:PartPicker', rsp);
351           },
352         });
353       } else {
354         this.$real.trigger('set_item:PartPicker', item);
355       }
356       this.annotate_state();
357     },
358     make_defined_state: function() {
359       if (this.state == this.STATES.PICKED) {
360         this.annotate_state();
361         return true
362       } else if (this.state == this.STATES.UNDEFINED && this.$dummy.val() === '')
363         this.set_item({})
364       else {
365         this.set_item({ id: this.last_real, name: this.last_dummy })
366       }
367       this.annotate_state();
368     },
369     annotate_state: function() {
370       if (this.state == this.STATES.PICKED)
371         this.$dummy.removeClass(this.STATES.UNDEFINED).addClass(this.STATES.PICKED);
372       else if (this.state == this.STATES.UNDEFINED && this.$dummy.val() === '')
373         this.$dummy.removeClass(this.STATES.UNDEFINED).addClass(this.STATES.PICKED);
374       else {
375         this.$dummy.addClass(this.STATES.UNDEFINED).removeClass(this.STATES.PICKED);
376       }
377     },
378     handle_changed_text: function(callbacks) {
379       var self = this;
380       $.ajax({
381         url: 'controller.pl?action=Part/ajax_autocomplete',
382         dataType: "json",
383         data: $.extend( self.ajax_data(self.$dummy.val()), { prefer_exact: 1 } ),
384         success: function (data) {
385           if (data.length == 1) {
386             self.set_item(data[0]);
387             if (callbacks && callbacks.match_one) callbacks.match_one(data[0]);
388           } else if (data.length > 1) {
389             self.state = self.STATES.UNDEFINED;
390             if (callbacks && callbacks.match_many) callbacks.match_many(data);
391           } else {
392             self.state = self.STATES.UNDEFINED;
393             if (callbacks && callbacks.match_none) callbacks.match_none();
394           }
395           self.annotate_state();
396         }
397       });
398     },
399     /*  In case users are impatient and want to skip ahead:
400      *  Capture <enter> key events and check if it's a unique hit.
401      *  If it is, go ahead and assume it was selected. If it wasn't don't do
402      *  anything so that autocompletion kicks in.  For <tab> don't prevent
403      *  propagation. It would be nice to catch it, but javascript is too stupid
404      *  to fire a tab event later on, so we'd have to reimplement the "find
405      *  next active element in tabindex order and focus it".
406      */
407     /* note:
408      *  event.which does not contain tab events in keypressed in firefox but will report 0
409      *  chrome does not fire keypressed at all on tab or escape
410      */
411     handle_keydown: function(event) {
412       var self = this;
413       if (event.which == KEY.ENTER || event.which == KEY.TAB) {
414         // if string is empty assume they want to delete
415         if (self.$dummy.val() === '') {
416           self.set_item({});
417           return true;
418         } else if (self.state == self.STATES.PICKED) {
419           return true;
420         }
421         if (event.which == KEY.TAB) {
422           event.preventDefault();
423           self.handle_changed_text();
424         }
425         if (event.which == KEY.ENTER) {
426           self.handle_changed_text({
427             match_one:  self.o.action.on_enter_match_one,
428             match_many: self.o.action.on_enter_match_many
429           });
430           return false;
431         }
432       } else if (event.which == KEY.DOWN && !self.autocomplete_open) {
433         var old_options = self.$dummy.autocomplete('option');
434         self.$dummy.autocomplete('option', 'minLength', 0);
435         self.$dummy.autocomplete('search', self.$dummy.val());
436         self.$dummy.autocomplete('option', 'minLength', old_options.minLength);
437       } else if ((event.which != KEY.SHIFT) && (event.which != KEY.CTRL) && (event.which != KEY.ALT)) {
438         self.state = self.STATES.UNDEFINED;
439       }
440     },
441     open_dialog: function() {
442       new ns.PickerPopup(this);
443     },
444     init: function() {
445       var self = this;
446       this.$dummy.autocomplete({
447         source: function(req, rsp) {
448           $.ajax($.extend(self.o, {
449             url:      'controller.pl?action=Part/ajax_autocomplete',
450             dataType: "json",
451             data:     self.ajax_data(req.term),
452             success:  function (data){ rsp(data) }
453           }));
454         },
455         select: function(event, ui) {
456           self.set_item(ui.item);
457         },
458         search: function(event, ui) {
459           if ((event.which == KEY.SHIFT) || (event.which == KEY.CTRL) || (event.which == KEY.ALT))
460             event.preventDefault();
461         },
462         open: function() {
463           self.autocomplete_open = true;
464         },
465         close: function() {
466           self.autocomplete_open = false;
467         }
468       });
469       this.$dummy.keydown(function(event){ self.handle_keydown(event) });
470       this.$dummy.on('paste', function(){
471         setTimeout(function() {
472           self.handle_changed_text();
473         }, 1);
474       });
475       this.$dummy.blur(function(){
476         window.clearTimeout(self.timer);
477         self.timer = window.setTimeout(function() { self.annotate_state() }, 100);
478       });
479
480       var popup_button = $('<span>').addClass('ppp_popup_button');
481       this.$dummy.after(popup_button);
482       popup_button.click(function() { self.open_dialog() });
483     }
484   };
485   ns.Picker.prototype.STATES = {
486     PICKED:    ns.Picker.prototype.CLASSES.PICKED,
487     UNDEFINED: ns.Picker.prototype.CLASSES.UNDEFINED
488   };
489
490   ns.PickerPopup = function(pp) {
491     this.timer = undefined;
492     this.pp    = pp;
493     this.open_dialog();
494   };
495
496   ns.PickerPopup.prototype = {
497     open_dialog: function() {
498       var self = this;
499       kivi.popup_dialog({
500         url: 'controller.pl?action=Part/part_picker_search',
501         data: $.extend({
502           real_id: self.pp.real_id,
503         }, self.pp.ajax_data(this.pp.$dummy.val())),
504         id: 'part_selection',
505         dialog: {
506           title: kivi.t8('Part picker'),
507           width: 800,
508           height: 800,
509         },
510         load: function() { self.init_search(); }
511       });
512       window.clearTimeout(this.timer);
513       return true;
514     },
515     init_search: function() {
516       var self = this;
517       $('#part_picker_filter').keypress(function(e) { self.result_timer(e) }).focus();
518       $('#no_paginate').change(function() { self.update_results() });
519       this.update_results();
520     },
521     update_results: function() {
522       var self = this;
523       $.ajax({
524         url: 'controller.pl?action=Part/part_picker_result',
525         data: $.extend({
526          'real_id':    self.pp.$real.val(),
527           no_paginate: $('#no_paginate').prop('checked') ? 1 : 0,
528         }, self.pp.ajax_data(function(){
529           var val = $('#part_picker_filter').val();
530           return val === undefined ? '' : val
531         })),
532         success: function(data){
533           $('#part_picker_result').html(data);
534           self.init_results();
535         }
536       });
537     },
538     init_results: function() {
539       var self = this;
540       $('div.part_picker_part').each(function(){
541         $(this).click(function(){
542           self.pp.set_item({
543             id:   $(this).children('input.part_picker_id').val(),
544             name: $(this).children('input.part_picker_description').val(),
545             classification_id: $(this).children('input.part_picker_classification_id').val(),
546             unit: $(this).children('input.part_picker_unit').val(),
547             partnumber:  $(this).children('input.part_picker_partnumber').val(),
548             description: $(this).children('input.part_picker_description').val(),
549           });
550           self.close_popup();
551           self.pp.$dummy.focus();
552           return true;
553         });
554       });
555       $('#part_selection').keydown(function(e){
556          if (e.which == KEY.ESCAPE) {
557            self.close_popup();
558            self.pp.$dummy.focus();
559          }
560       });
561     },
562     result_timer: function(event) {
563       var self = this;
564       if (!$('no_paginate').prop('checked')) {
565         if (event.keyCode == KEY.PAGE_UP) {
566           $('#part_picker_result a.paginate-prev').click();
567           return;
568         }
569         if (event.keyCode == KEY.PAGE_DOWN) {
570           $('#part_picker_result a.paginate-next').click();
571           return;
572         }
573       }
574       window.clearTimeout(this.timer);
575       if (event.which == KEY.ENTER) {
576         self.update_results();
577       } else {
578         this.timer = window.setTimeout(function() { self.update_results() }, 100);
579       }
580     },
581     close_popup: function() {
582       $('#part_selection').dialog('close');
583     }
584   };
585
586   ns.reinit_widgets = function() {
587     kivi.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
588       if (!$(elt).data('part_picker'))
589         $(elt).data('part_picker', new kivi.Part.Picker($(elt)));
590     });
591   }
592
593   ns.init = function() {
594     ns.reinit_widgets();
595   }
596
597   $(function(){
598
599     // assortment
600     // TODO: allow units for assortment items
601     $('#add_assortment_item_id').on('set_item:PartPicker', function(e,o) { $('#add_item_unit').val(o.unit) });
602
603     $('#ic').on('focusout', '.reformat_number', function(event) {
604        ns.reformat_number(event);
605     })
606
607     $('.add_assortment_item_input').keydown(function(event) {
608       if(event.keyCode == 13) {
609         event.preventDefault();
610         if ($("input[name='add_items[+].parts_id']").val() !== '' ) {
611           kivi.Part.show_multi_items_dialog("assortment");
612          // ns.add_assortment_item();
613         }
614         return false;
615       }
616     });
617
618     $('.add_assembly_item_input').keydown(function(event) {
619       if(event.keyCode == 13) {
620         event.preventDefault();
621         if ($("input[name='add_items[+].parts_id']").val() !== '' ) {
622           kivi.Part.show_multi_items_dialog("assortment");
623           // ns.add_assembly_item();
624         }
625         return false;
626       }
627     });
628
629     $('.add_makemodel_input').keydown(function(event) {
630       if(event.keyCode == 13) {
631         event.preventDefault();
632         ns.add_makemodel_row();
633         return false;
634       }
635     });
636
637     $('#part_warehouse_id').change(kivi.Part.reload_bin_selection);
638
639     ns.init();
640   });
641 });