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