Ansprechpartner um boolean Hauptansprechpartner erweitert
[kivitendo-erp.git] / js / kivi.CustomerVendor.js
1 namespace('kivi.CustomerVendor', function(ns) {
2
3   this.selectShipto = function(params) {
4     var shiptoId = $('#shipto_shipto_id').val();
5     var url      = 'controller.pl?action=CustomerVendor/ajaj_get_shipto&id='+ $('#cv_id').val() +'&db='+ $('#db').val() +'&shipto_id='+ shiptoId;
6
7     $.getJSON(url, function(data) {
8       var shipto = data.shipto;
9       for(var key in shipto)
10         $('#shipto_'+ key).val(shipto[key])
11
12       kivi.CustomerVendor.setCustomVariablesFromAJAJ(data.shipto_cvars, 'shipto_cvars_');
13
14       if ( shiptoId )
15         $('#action_delete_shipto').show();
16       else
17         $('#action_delete_shipto').hide();
18
19       if ( params.onFormSet )
20         params.onFormSet();
21     });
22   };
23
24   this.selectDelivery = function(fromDate, toDate) {
25     var deliveryId = $('#delivery_id').val();
26
27     if( !deliveryId )
28       $("#delivery").empty();
29     else {
30       var url = 'controller.pl?action=CustomerVendor/get_delivery&id='+ $('#cv_id').val() +'&db='+ $('#db').val() +'&shipto_id='+ $('#delivery_id').val();
31
32       if( fromDate && toDate )
33         url += '&delivery_from='+ fromDate +'&delivery_to='+ toDate;
34
35       $('#delivery').load(url);
36     }
37   };
38
39   this.setCustomVariablesFromAJAJ = function(cvars, prefix) {
40     for (var key in cvars) {
41       var cvar  = cvars[key];
42       var $ctrl = $('#' + prefix + key);
43
44       if (cvar.type == 'bool')
45         $ctrl.prop('checked', cvar.value == 1 ? 'checked' : '');
46
47       else if ((cvar.type == 'customer') || (cvar.type == 'vendor'))
48         kivi.CustomerVendor.Picker($ctrl).set_item({ id: cvar.id, name: cvar.value });
49
50       else if (cvar.type == 'part')
51         kivi.Part.Picker($ctrl).set_item({ id: cvar.id, name: cvar.value });
52
53       else
54         $ctrl.val(cvar.value);
55     }
56   };
57
58   this.selectContact = function(params) {
59     var contactId = $('#contact_cp_id').val();
60
61           var url = 'controller.pl?action=CustomerVendor/ajaj_get_contact&id='+ $('#cv_id').val() +'&db='+ $('#db').val() +'&contact_id='+ contactId;
62
63     $.getJSON(url, function(data) {
64       var contact = data.contact;
65       for(var key in contact)
66         $('#contact_'+ key).val(contact[key])
67
68       kivi.CustomerVendor.setCustomVariablesFromAJAJ(data.contact_cvars, 'contact_cvars_');
69
70       if ( contactId )
71         $('#action_delete_contact').show();
72       else
73         $('#action_delete_contact').hide();
74       if (data.contact.disable_cp_main === 1)
75         $("#contact_cp_main").prop("disabled", true);
76       else
77         $("#contact_cp_main").prop("disabled", false);
78       if ( params.onFormSet )
79         params.onFormSet();
80     });
81
82     $('#contact_cp_title_select, #contact_cp_abteilung_select').val('');
83   };
84
85   var mapSearchStmts = [
86     '#street',
87     ', ',
88     '#zipcode',
89     ' ',
90     '#city',
91     ', ',
92     '#country'
93   ];
94
95   this.MapWidget = function(prefix, source_address)
96   {
97     var $mapSearchElements = [];
98     var $widgetWrapper;
99
100     var init = function() {
101       if( $mapSearchElements.length > 0 )
102         return;
103
104       for(var i in mapSearchStmts) {
105         var stmt = mapSearchStmts[i];
106         if( stmt.charAt(0) == '#' ) {
107           var $elem = $('#'+ prefix + stmt.substring(1));
108           if( $elem )
109             $mapSearchElements.push($elem);
110         }
111       }
112     };
113
114     var isNotEmpty = function() {
115       for(var i in $mapSearchElements)
116         if( ($mapSearchElements[i].attr('id') != prefix + 'country') && ($mapSearchElements[i].val() === '') )
117           return false;
118       return true;
119     };
120
121     var showMap = function() {
122       var searchString = "";
123
124       for(var i in mapSearchStmts) {
125         var stmt = mapSearchStmts[i];
126         if( stmt.charAt(0) == '#' ) {
127           var val = $('#'+ prefix + stmt.substring(1)).val();
128           if( val )
129             searchString += val;
130         }
131         else
132           searchString += stmt;
133       }
134
135       source_address = source_address || '';
136       var query      = source_address !== '' ? 'saddr=' + encodeURIComponent(source_address) + '&daddr=' : 'q=';
137       var url        = 'https://maps.google.com/maps?' + query + encodeURIComponent(searchString);
138
139       window.open(url, '_blank');
140       window.focus();
141     };
142
143     var render = function(widgetWrapper) {
144       init();
145
146       $widgetWrapper = $(widgetWrapper);
147
148       $widgetWrapper
149         .html('<img src="image/map.png" alt="'+ kivi.t8("Map") +'" title="'+ kivi.t8("Map") +'" />')
150         .click(function() {
151           showMap();
152         });
153       for(var i in $mapSearchElements)
154         $mapSearchElements[i].keyup(testInputs);
155       this.testInputs();
156     };
157
158     var testInputs = function() {
159       init();
160
161       if( isNotEmpty() )
162         $widgetWrapper.show();
163       else
164         $widgetWrapper.hide();
165     };
166
167     this.render = render;
168     this.testInputs = testInputs;
169   };
170
171   this.showHistoryWindow = function(id) {
172     var xPos = (screen.width - 800) / 2;
173     var yPos = (screen.height - 500) / 2;
174     var parm = "left="+ xPos +",top="+ yPos +",width=800,height=500,status=yes,scrollbars=yes";
175     var url = "common.pl?INPUT_ENCODING=UTF-8&action=show_history&longdescription=&input_name="+ encodeURIComponent(id);
176     window.open(url, "_new_generic", parm);
177   };
178
179   this.update_dial_action = function($input) {
180     var $action = $('#' + $input.prop('id') + '-dial-action');
181
182     if (!$action)
183       return true;
184
185     var number = $input.val().replace(/\s+/g, '');
186     if (number === '')
187       $action.hide();
188     else
189       $action.prop('href', 'controller.pl?action=CTI/call&number=' + encodeURIComponent(number)).show();
190
191     return true;
192   };
193
194   this.init_dial_action = function(input) {
195     if ($('#_cti_enabled').val() != 1)
196       return false;
197
198     var $input    = $(input);
199     var action_id = $input.prop('id') + '-dial-action';
200
201     if (!$('#' + action_id).size()) {
202       var $action = $('<a href="" id="' + action_id + '" class="cti_call_action" target="_blank" tabindex="-1"></a>');
203       $input.wrap('<span nobr></span>').after($action);
204
205       $input.change(function() { kivi.CustomerVendor.update_dial_action($input); });
206     }
207
208     kivi.CustomerVendor.update_dial_action($input);
209
210     return true;
211   };
212
213   this.inline_report = function(target, source, data){
214 //    alert("HALLO S " + source + " --T " + target + " tt D " + data);
215     $.ajax({
216       url:        source,
217       success:    function (rsp) {
218         $(target).html(rsp);
219         $(target).find('.paginate').find('a').click(function(event){ ns.redirect_event(event, target) });
220         $(target).find('a.report-generator-header-link').click(function(event){ ns.redirect_event(event, target) });
221       },
222       data:       data,
223     });
224   };
225   this.redirect_event = function(event, target){
226     event.preventDefault();
227     ns.inline_report(target, event.target + '', {});
228   };
229
230   var KEY = {
231     TAB:       9,
232     ENTER:     13,
233     SHIFT:     16,
234     CTRL:      17,
235     ALT:       18,
236     ESCAPE:    27,
237     PAGE_UP:   33,
238     PAGE_DOWN: 34,
239     LEFT:      37,
240     UP:        38,
241     RIGHT:     39,
242     DOWN:      40,
243   };
244
245   ns.Picker = function($real, options) {
246     var self = this;
247     this.o = $.extend(true, {
248       limit: 20,
249       delay: 50,
250       action: {
251         commit_none: function(){ },
252         commit_one:  function(){ $('#update_button').click(); },
253         commit_many: function(){ }
254       }
255     }, $real.data('customer-vendor-picker-data'), options);
256     this.$real              = $real;
257     this.real_id            = $real.attr('id');
258     this.last_real          = $real.val();
259     this.$dummy             = $($real.siblings()[0]);
260     this.autocomplete_open  = false;
261     this.state              = this.STATES.PICKED;
262     this.last_dummy         = this.$dummy.val();
263     this.timer              = undefined;
264
265     this.init();
266   };
267
268   ns.Picker.prototype = {
269     CLASSES: {
270       PICKED:       'customer-vendor-picker-picked',
271       UNDEFINED:    'customer-vendor-picker-undefined',
272     },
273     ajax_data: function(term) {
274       return {
275         'filter.all:substr:multi::ilike': term,
276         'filter.obsolete': 0,
277         current:  this.$real.val(),
278         type:     this.o.cv_type,
279       };
280     },
281     set_item: function(item) {
282       var self = this;
283       if (item.id) {
284         this.$real.val(item.id);
285         // autocomplete ui has name, use the value for ajax items, which contains displayable_name
286         this.$dummy.val(item.name ? item.name : item.value);
287       } else {
288         this.$real.val('');
289         this.$dummy.val('');
290       }
291       this.state      = this.STATES.PICKED;
292       this.last_real  = this.$real.val();
293       this.last_dummy = this.$dummy.val();
294       this.$real.trigger('change');
295
296       if (this.o.fat_set_item && item.id) {
297         $.ajax({
298           url: 'controller.pl?action=CustomerVendor/show.json',
299           data: { 'id': item.id, 'db': item.type },
300           success: function(rsp) {
301             self.$real.trigger('set_item:CustomerVendorPicker', rsp);
302           },
303         });
304       } else {
305         this.$real.trigger('set_item:CustomerVendorPicker', item);
306       }
307       this.annotate_state();
308     },
309     set_multi_items: function(data) {
310       this.run_action(this.o.action.set_multi_items, [ data ]);
311     },
312     make_defined_state: function() {
313       if (this.state == this.STATES.PICKED) {
314         this.annotate_state();
315         return true
316       } else if (this.state == this.STATES.UNDEFINED && this.$dummy.val() === '')
317         this.set_item({})
318       else {
319         this.set_item({ id: this.last_real, name: this.last_dummy })
320       }
321       this.annotate_state();
322     },
323     annotate_state: function() {
324       if (this.state == this.STATES.PICKED)
325         this.$dummy.removeClass(this.STATES.UNDEFINED).addClass(this.STATES.PICKED);
326       else if (this.state == this.STATES.UNDEFINED && this.$dummy.val() === '')
327         this.$dummy.removeClass(this.STATES.UNDEFINED).addClass(this.STATES.PICKED);
328       else {
329         this.$dummy.addClass(this.STATES.UNDEFINED).removeClass(this.STATES.PICKED);
330       }
331     },
332     handle_changed_text: function(callbacks) {
333       var self = this;
334       $.ajax({
335         url: 'controller.pl?action=CustomerVendor/ajaj_autocomplete',
336         dataType: "json",
337         data: $.extend( self.ajax_data(self.$dummy.val()), { prefer_exact: 1 } ),
338         success: function (data) {
339           if (data.length == 1) {
340             self.set_item(data[0]);
341             if (callbacks && callbacks.match_one) self.run_action(callbacks.match_one, [ data[0] ]);
342           } else if (data.length > 1) {
343             self.state = self.STATES.UNDEFINED;
344             if (callbacks && callbacks.match_many) self.run_action(callbacks.match_many, [ data ]);
345           } else {
346             self.state = self.STATES.UNDEFINED;
347             if (callbacks && callbacks.match_none) self.run_action(callbacks.match_none, [ self, self.$dummy.val() ]);
348           }
349           self.annotate_state();
350         }
351       });
352     },
353     handle_keydown: function(event) {
354       var self = this;
355       if (event.which == KEY.ENTER || event.which == KEY.TAB) {
356         // if string is empty assume they want to delete
357         if (self.$dummy.val() === '') {
358           self.set_item({});
359           return true;
360         } else if (self.state == self.STATES.PICKED) {
361           if (self.o.action.commit_one) {
362             self.run_action(self.o.action.commit_one);
363           }
364           return true;
365         }
366         if (event.which == KEY.TAB) {
367           event.preventDefault();
368           self.handle_changed_text();
369         }
370         if (event.which == KEY.ENTER) {
371           event.preventDefault();
372           self.handle_changed_text({
373             match_none: self.o.action.commit_none,
374             match_one:  self.o.action.commit_one,
375             match_many: self.o.action.commit_many
376           });
377           return false;
378         }
379       } else if (event.which == KEY.DOWN && !self.autocomplete_open) {
380         var old_options = self.$dummy.autocomplete('option');
381         self.$dummy.autocomplete('option', 'minLength', 0);
382         self.$dummy.autocomplete('search', self.$dummy.val());
383         self.$dummy.autocomplete('option', 'minLength', old_options.minLength);
384       } else if ((event.which != KEY.SHIFT) && (event.which != KEY.CTRL) && (event.which != KEY.ALT)) {
385         self.state = self.STATES.UNDEFINED;
386       }
387     },
388     init: function() {
389       var self = this;
390       this.$dummy.autocomplete({
391         source: function(req, rsp) {
392           $.ajax($.extend({}, self.o, {
393             url:      'controller.pl?action=CustomerVendor/ajaj_autocomplete',
394             dataType: "json",
395             type:     'get',
396             data:     self.ajax_data(req.term),
397             success:  function (data){ rsp(data) }
398           }));
399         },
400         select: function(event, ui) {
401           self.set_item(ui.item);
402           if (self.o.action.commit_one) {
403             self.run_action(self.o.action.commit_one);
404           }
405         },
406         search: function(event, ui) {
407           if ((event.which == KEY.SHIFT) || (event.which == KEY.CTRL) || (event.which == KEY.ALT))
408             event.preventDefault();
409         },
410         open: function() {
411           self.autocomplete_open = true;
412         },
413         close: function() {
414           self.autocomplete_open = false;
415         }
416       });
417       this.$dummy.keydown(function(event){ self.handle_keydown(event) });
418       this.$dummy.on('paste', function(){
419         setTimeout(function() {
420           self.handle_changed_text();
421         }, 1);
422       });
423       this.$dummy.blur(function(){
424         window.clearTimeout(self.timer);
425         self.timer = window.setTimeout(function() { self.annotate_state() }, 100);
426       });
427     },
428     run_action: function(code, args) {
429       if (typeof code === 'function')
430         code.apply(this, args)
431       else
432         kivi.run(code, args);
433     },
434     clear: function() {
435       this.set_item({});
436     }
437   };
438   ns.Picker.prototype.STATES = {
439     PICKED:    ns.Picker.prototype.CLASSES.PICKED,
440     UNDEFINED: ns.Picker.prototype.CLASSES.UNDEFINED
441   };
442
443   ns.reinit_widgets = function() {
444     kivi.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
445       if (!$(elt).data('customer_vendor_picker'))
446         $(elt).data('customer_vendor_picker', new kivi.CustomerVendor.Picker($(elt)));
447     });
448
449     $('#cv_phone,#shipto_shiptophone,#contact_cp_phone1,#contact_cp_phone2,#contact_cp_mobile1,#contact_cp_mobile2').each(function(idx, elt) {
450       kivi.CustomerVendor.init_dial_action($(elt));
451     });
452   }
453
454   ns.init = function() {
455     ns.reinit_widgets();
456   }
457
458   $(function(){
459     ns.init();
460   });
461 });