partpicker mit classification_id als filter erweitert
[kivitendo-erp.git] / js / autocomplete_part.js
1 namespace('kivi', function(k){
2   k.PartPicker = function($real, options) {
3     // short circuit in case someone double inits us
4     if ($real.data("part_picker"))
5       return $real.data("part_picker");
6
7     var KEY = {
8       ESCAPE: 27,
9       ENTER:  13,
10       TAB:    9,
11       LEFT:   37,
12       RIGHT:  39,
13       PAGE_UP: 33,
14       PAGE_DOWN: 34,
15     };
16     var CLASSES = {
17       PICKED:       'partpicker-picked',
18       UNDEFINED:    'partpicker-undefined',
19       FAT_SET_ITEM: 'partpicker_fat_set_item',
20     }
21     var o = $.extend({
22       limit: 20,
23       delay: 50,
24       fat_set_item: $real.hasClass(CLASSES.FAT_SET_ITEM),
25     }, options);
26     var STATES = {
27       PICKED:    CLASSES.PICKED,
28       UNDEFINED: CLASSES.UNDEFINED
29     }
30     var real_id = $real.attr('id');
31     var $dummy             = $('#' + real_id + '_name');
32     var $part_type         = $('#' + real_id + '_part_type');
33     var $classification_id = $('#' + real_id + '_classification_id');
34     var $unit              = $('#' + real_id + '_unit');
35     var $convertible_unit  = $('#' + real_id + '_convertible_unit');
36     var state   = STATES.PICKED;
37     var last_real = $real.val();
38     var last_dummy = $dummy.val();
39     var timer;
40
41     function open_dialog () {
42       k.popup_dialog({
43         url: 'controller.pl?action=Part/part_picker_search',
44         data: $.extend({
45           real_id: real_id,
46         }, ajax_data($dummy.val())),
47         id: 'part_selection',
48         dialog: {
49           title: k.t8('Part picker'),
50           width: 800,
51           height: 800,
52         }
53       });
54       window.clearTimeout(timer);
55       return true;
56     }
57
58     function ajax_data(term) {
59       var data = {
60         'filter.all:substr:multi::ilike': term,
61         'filter.obsolete': 0,
62         'filter.unit_obj.convertible_to': $convertible_unit && $convertible_unit.val() ? $convertible_unit.val() : '',
63         no_paginate:  $('#no_paginate').prop('checked') ? 1 : 0,
64         current:  $real.val(),
65       };
66
67       if ($part_type && $part_type.val())
68         data['filter.part_type'] = $part_type.val().split(',');
69
70       if ($classification_id && $classification_id.val())
71         data['filter.classification_id'] = $classification_id.val().split(',');
72
73       if ($unit && $unit.val())
74         data['filter.unit'] = $unit.val().split(',');
75
76       return data;
77     }
78
79     function set_item (item) {
80       if (item.id) {
81         $real.val(item.id);
82         // autocomplete ui has name, use the value for ajax items, which contains displayable_name
83         $dummy.val(item.name ? item.name : item.value);
84       } else {
85         $real.val('');
86         $dummy.val('');
87       }
88       state = STATES.PICKED;
89       last_real = $real.val();
90       last_dummy = $dummy.val();
91       last_unverified_dummy = $dummy.val();
92       $real.trigger('change');
93
94       if (o.fat_set_item && item.id) {
95         $.ajax({
96           url: 'controller.pl?action=Part/show.json',
97           data: { id: item.id },
98           success: function(rsp) {
99             $real.trigger('set_item:PartPicker', rsp);
100           },
101         });
102       } else {
103         $real.trigger('set_item:PartPicker', item);
104       }
105       annotate_state();
106     }
107
108     function make_defined_state () {
109       if (state == STATES.PICKED) {
110         annotate_state();
111         return true
112       } else if (state == STATES.UNDEFINED && $dummy.val() == '')
113         set_item({})
114       else {
115         last_unverified_dummy = $dummy.val();
116         set_item({ id: last_real, name: last_dummy })
117       }
118       annotate_state();
119     }
120
121     function annotate_state () {
122       if (state == STATES.PICKED)
123         $dummy.removeClass(STATES.UNDEFINED).addClass(STATES.PICKED);
124       else if (state == STATES.UNDEFINED && $dummy.val() == '')
125         $dummy.removeClass(STATES.UNDEFINED).addClass(STATES.PICKED);
126       else {
127         last_unverified_dummy = $dummy.val();
128         $dummy.addClass(STATES.UNDEFINED).removeClass(STATES.PICKED);
129       }
130     }
131
132     function update_results () {
133       $.ajax({
134         url: 'controller.pl?action=Part/part_picker_result',
135         data: $.extend({
136             'real_id': $real.val(),
137         }, ajax_data(function(){ var val = $('#part_picker_filter').val(); return val === undefined ? '' : val })),
138         success: function(data){ $('#part_picker_result').html(data) }
139       });
140     };
141
142     function result_timer (event) {
143       if (!$('no_paginate').prop('checked')) {
144         if (event.keyCode == KEY.PAGE_UP) {
145           $('#part_picker_result a.paginate-prev').click();
146           return;
147         }
148         if (event.keyCode == KEY.PAGE_DOWN) {
149           $('#part_picker_result a.paginate-next').click();
150           return;
151         }
152       }
153       window.clearTimeout(timer);
154       timer = window.setTimeout(update_results, 100);
155     }
156
157     function close_popup() {
158       $('#part_selection').dialog('close');
159     };
160
161     function handle_changed_text(callbacks) {
162       $.ajax({
163         url: 'controller.pl?action=Part/ajax_autocomplete',
164         dataType: "json",
165         data: $.extend( ajax_data($dummy.val()), { prefer_exact: 1 } ),
166         success: function (data) {
167           if (data.length == 1) {
168             set_item(data[0]);
169             if (callbacks && callbacks.match_one) callbacks.match_one(data[0]);
170           } else if (data.length > 1) {
171             state = STATES.UNDEFINED;
172             if (callbacks && callbacks.match_many) callbacks.match_many(data);
173           } else {
174             state = STATES.UNDEFINED;
175             if (callbacks &&callbacks.match_none) callbacks.match_none();
176           }
177           annotate_state();
178         }
179       });
180     };
181
182     $dummy.autocomplete({
183       source: function(req, rsp) {
184         $.ajax($.extend(o, {
185           url:      'controller.pl?action=Part/ajax_autocomplete',
186           dataType: "json",
187           data:     ajax_data(req.term),
188           success:  function (data){ rsp(data) }
189         }));
190       },
191       select: function(event, ui) {
192         set_item(ui.item);
193       },
194     });
195     /*  In case users are impatient and want to skip ahead:
196      *  Capture <enter> key events and check if it's a unique hit.
197      *  If it is, go ahead and assume it was selected. If it wasn't don't do
198      *  anything so that autocompletion kicks in.  For <tab> don't prevent
199      *  propagation. It would be nice to catch it, but javascript is too stupid
200      *  to fire a tab event later on, so we'd have to reimplement the "find
201      *  next active element in tabindex order and focus it".
202      */
203     /* note:
204      *  event.which does not contain tab events in keypressed in firefox but will report 0
205      *  chrome does not fire keypressed at all on tab or escape
206      */
207     $dummy.keydown(function(event){
208       if (event.which == KEY.ENTER || event.which == KEY.TAB) {
209         // if string is empty assume they want to delete
210         if ($dummy.val() == '') {
211           set_item({});
212           return true;
213         } else if (state == STATES.PICKED) {
214           return true;
215         }
216         if (event.which == KEY.TAB) {
217           event.preventDefault();
218           handle_changed_text();
219         }
220         if (event.which == KEY.ENTER) {
221           handle_changed_text({
222             match_one:  function(){$('#update_button').click();},
223             match_many: function(){open_dialog();}
224           });
225           return false;
226         }
227       } else {
228         state = STATES.UNDEFINED;
229       }
230     });
231
232     $dummy.on('paste', function(){
233       setTimeout(function() {
234         handle_changed_text();
235       }, 1);
236     });
237
238     $dummy.blur(function(){
239       window.clearTimeout(timer);
240       timer = window.setTimeout(annotate_state, 100);
241     });
242
243     // now add a picker div after the original input
244     var popup_button = $('<span>').addClass('ppp_popup_button');
245     $dummy.after(popup_button);
246     popup_button.click(open_dialog);
247
248     var pp = {
249       real:              function() { return $real },
250       dummy:             function() { return $dummy },
251       part_type:         function() { return $part_type },
252       classification_id: function() { return $classification_id },
253       unit:              function() { return $unit },
254       convertible_unit:  function() { return $convertible_unit },
255       update_results: update_results,
256       result_timer:   result_timer,
257       set_item:       set_item,
258       reset:          make_defined_state,
259       is_defined_state: function() { return state == STATES.PICKED },
260       init_results:    function () {
261         $('div.part_picker_part').each(function(){
262           $(this).click(function(){
263             set_item({
264               id:   $(this).children('input.part_picker_id').val(),
265               name: $(this).children('input.part_picker_description').val(),
266               classification_id: $(this).children('input.part_picker_classification_id').val(),
267               unit: $(this).children('input.part_picker_unit').val(),
268               partnumber:  $(this).children('input.part_picker_partnumber').val(),
269               description: $(this).children('input.part_picker_description').val(),
270             });
271             close_popup();
272             $dummy.focus();
273             return true;
274           });
275         });
276         $('#part_selection').keydown(function(e){
277            if (e.which == KEY.ESCAPE) {
278              close_popup();
279              $dummy.focus();
280            }
281         });
282       }
283     }
284     $real.data('part_picker', pp);
285     return pp;
286   }
287 });
288
289 $(function(){
290   $('input.part_autocomplete').each(function(i,real){
291     kivi.PartPicker($(real));
292   })
293 });