]> wagnertech.de Git - mfinanz.git/blob - js/kivi.Reclamation.js
date error in mapping
[mfinanz.git] / js / kivi.Reclamation.js
1 namespace('kivi.Reclamation', function(ns) {
2   ns.check_cv = function() {
3     if ($('#type').val() == 'sales_reclamation') {
4       if ($('#reclamation_customer_id').val() === '') {
5         alert(kivi.t8('Please select a customer.'));
6         return false;
7       }
8     } else  {
9       if ($('#reclamation_vendor_id').val() === '') {
10         alert(kivi.t8('Please select a vendor.'));
11         return false;
12       }
13     }
14     return true;
15   };
16
17   ns.check_duplicate_parts = function(question) {
18     var id_arr = $('[name="reclamation.reclamation_items[].parts_id"]').map(function() { return this.value; }).get();
19
20     var i, obj = {}, pos = [];
21
22     for (i = 0; i < id_arr.length; i++) {
23       var id = id_arr[i];
24       if (obj.hasOwnProperty(id)) {
25         pos.push(i + 1);
26       }
27       obj[id] = 0;
28     }
29
30     if (pos.length > 0) {
31       question = question || kivi.t8("Do you really want to continue?");
32       return confirm(kivi.t8("There are duplicate parts at positions") + "\n"
33                      + pos.join(', ') + "\n"
34                      + question);
35     }
36     return true;
37   };
38
39   ns.check_valid_reqdate = function() {
40     if ($('#reclamation_reqdate_as_date').val() === '') {
41       alert(kivi.t8('Please select a deadline date.'));
42       return false;
43     } else {
44       return true;
45     }
46   };
47
48   ns.check_valid_reasons = function() {
49     var positions_with_empty = [];
50
51     $('.row_entry').each(function(idx, elt) {
52       if ($(elt).find('[name="reclamation.reclamation_items[].reason_id"]').val() == '') {
53         positions_with_empty.push(idx+1);
54       }
55     });
56
57     if (positions_with_empty.length > 0) {
58       alert(kivi.t8("There are parts with no reclamation reason at position:") + "\n"
59             + positions_with_empty.join(', ') );
60       return false;
61     } else {
62       return true;
63     }
64   };
65
66   ns.save = function(params) {
67     if (!ns.check_cv()) return;
68
69     const action             = params.action;
70     const warn_on_duplicates = params.warn_on_duplicates;
71     const warn_on_reqdate    = params.warn_on_reqdate;
72     const form_params        = params.form_params;
73
74     if (warn_on_duplicates && !ns.check_duplicate_parts()) return;
75     if (warn_on_reqdate    && !ns.check_valid_reqdate())   return;
76     if (!ns.check_valid_reasons())                     return;
77
78     var data = $('#reclamation_form').serializeArray();
79     data.push({ name: 'action', value: 'Reclamation/' + action });
80     if (form_params) {
81       if (Array.isArray(form_params)) {
82         form_params.forEach(function(item) {
83           data.push(item);
84         });
85       } else {
86         data.push(form_params);
87       }
88     }
89
90     $.post("controller.pl", data, kivi.eval_json_result);
91   };
92
93   ns.delete_reclamation = function() {
94     var data = $('#reclamation_form').serializeArray();
95     data.push({ name: 'action', value: 'Reclamation/delete' });
96
97     $.post("controller.pl", data, kivi.eval_json_result);
98   };
99
100   ns.show_print_options = function(warn_on_duplicates, warn_on_reqdate) {
101     if (!ns.check_cv()) return;
102     if (warn_on_duplicates && !ns.check_duplicate_parts(kivi.t8("Do you really want to print?"))) return;
103     if (warn_on_reqdate    && !ns.check_valid_reqdate())   return;
104
105     kivi.popup_dialog({
106       id: 'print_options',
107       dialog: {
108         title: kivi.t8('Print options'),
109         width:  800,
110         height: 300
111       }
112     });
113   };
114
115   ns.print = function() {
116     $('#print_options').dialog('close');
117
118     var data = $('#reclamation_form').serializeArray();
119     data = data.concat($('#print_options_form').serializeArray());
120     data.push({ name: 'action', value: 'Reclamation/print' });
121
122     $.post("controller.pl", data, kivi.eval_json_result);
123   };
124
125   var email_dialog;
126
127   ns.setup_send_email_dialog = function() {
128     kivi.SalesPurchase.show_all_print_options_elements();
129     kivi.SalesPurchase.show_print_options_elements([ 'sendmode', 'media', 'copies', 'remove_draft' ], false);
130
131     $('#print_options_form table').first().remove().appendTo('#email_form_print_options');
132
133     var to_focus = $('#email_form_to').val() === '' ? 'to' : 'subject';
134     $('#email_form_' + to_focus).focus();
135   };
136
137   ns.finish_send_email_dialog = function() {
138     kivi.SalesPurchase.show_all_print_options_elements();
139
140     $('#email_form_print_options table').first().remove().prependTo('#print_options_form');
141     return true;
142   };
143
144   ns.show_email_dialog = function(html) {
145     var id            = 'send_email_dialog';
146     var dialog_params = {
147       id:     id,
148       width:  800,
149       height: 600,
150       title:  kivi.t8('Send email'),
151       modal:  true,
152       beforeClose: kivi.Reclamation.finish_send_email_dialog,
153       close: function(event, ui) {
154         email_dialog.remove();
155       }
156     };
157
158     $('#' + id).remove();
159
160     email_dialog = $('<div style="display:none" id="' + id + '"></div>').appendTo('body');
161     email_dialog.html(html);
162     email_dialog.dialog(dialog_params);
163
164     kivi.Reclamation.setup_send_email_dialog();
165
166     $('.cancel').click(ns.close_email_dialog);
167
168     return true;
169   };
170
171   ns.send_email = function() {
172     // push button only once -> slow response from mail server
173     ns.email_dialog_disable_send();
174
175     var data = $('#reclamation_form').serializeArray();
176     data = data.concat($('[name^="email_form."]').serializeArray());
177     data = data.concat($('[name^="print_options."]').serializeArray());
178     data.push({ name: 'action', value: 'Reclamation/send_email' });
179     $.post("controller.pl", data, kivi.eval_json_result);
180   };
181
182   ns.email_dialog_disable_send = function() {
183     // disable mail send event to prevent
184     // impatient users to send multiple times
185     $('#send_email').prop('disabled', true);
186   };
187
188   ns.close_email_dialog = function() {
189     email_dialog.dialog("close");
190   };
191
192   ns.set_number_in_title = function(elt) {
193     $('#nr_in_title').html($(elt).val());
194   };
195
196   ns.reload_cv_dependent_selections = function() {
197     $('#reclamation_shipto_id').val('');
198     var data = $('#reclamation_form').serializeArray();
199     data.push({ name: 'action', value: 'Reclamation/customer_vendor_changed' });
200
201     $.post("controller.pl", data, kivi.eval_json_result);
202   };
203
204   ns.reformat_number = function(event) {
205     $(event.target).val(kivi.format_amount(kivi.parse_amount($(event.target).val()), -2));
206   };
207
208   ns.reformat_number_as_null_number = function(event) {
209     if ($(event.target).val() === '') {
210       return;
211     }
212     ns.reformat_number(event);
213   };
214
215   ns.update_exchangerate = function(event) {
216     if (!ns.check_cv()) {
217       $('#reclamation_currency_id').val($('#old_currency_id').val());
218       return;
219     }
220
221     var rate_input = $('#reclamation_exchangerate_as_null_number');
222     // unset exchangerate if currency changed
223     if ($('#reclamation_currency_id').val() !== $('#old_currency_id').val()) {
224       rate_input.val('');
225     }
226
227     // only set exchangerate if unset
228     if (rate_input.val() !== '') {
229       return;
230     }
231
232     var data = $('#reclamation_form').serializeArray();
233     data.push({ name: 'action', value: 'Reclamation/update_exchangerate' });
234
235     $.ajax({
236       url: 'controller.pl',
237       data: data,
238       method: 'POST',
239       dataType: 'json',
240       success: function(data){
241         if (!data.is_standard) {
242           $('#currency_name').text(data.currency_name);
243           if (data.exchangerate) {
244             rate_input.val(data.exchangerate);
245           } else {
246             rate_input.val('');
247           }
248           $('#reclamation_exchangerate_as_null_number').data('validate', 'required');
249           $('#exchangerate_settings').show();
250         } else {
251           rate_input.val('');
252           $('#reclamation_exchangerate_as_null_number').data('validate', '');
253           $('#exchangerate_settings').hide();
254         }
255         if ($('#reclamation_currency_id').val() != $('#old_currency_id').val() ||
256             !data.is_standard && data.exchangerate != $('#old_exchangerate').val()) {
257           kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
258         }
259         $('#old_currency_id').val($('#reclamation_currency_id').val());
260         $('#old_exchangerate').val(data.exchangerate);
261       }
262     });
263   };
264
265   ns.exchangerate_changed = function(event) {
266     if (kivi.parse_amount($('#reclamation_exchangerate_as_null_number').val()) != kivi.parse_amount($('#old_exchangerate').val())) {
267       kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
268       $('#old_exchangerate').val($('#reclamation_exchangerate_as_null_number').val());
269     }
270   };
271
272   ns.recalc_amounts_and_taxes = function() {
273     var data = $('#reclamation_form').serializeArray();
274     data.push({ name: 'action', value: 'Reclamation/recalc_amounts_and_taxes' });
275
276     $.post("controller.pl", data, kivi.eval_json_result);
277   };
278
279   ns.unit_change = function(event) {
280     var row           = $(event.target).parents("tbody").first();
281     var item_id_dom   = $(row).find('[name="reclamation_item_ids[+]"]');
282     var sellprice_dom = $(row).find('[name="reclamation.reclamation_items[].sellprice_as_number"]');
283     var select_elt    = $(row).find('[name="reclamation.reclamation_items[].unit"]');
284
285     var oldval = $(select_elt).data('oldval');
286     $(select_elt).data('oldval', $(select_elt).val());
287
288     var data = $('#reclamation_form').serializeArray();
289     data.push({ name: 'action',           value: 'Reclamation/unit_changed'     },
290               { name: 'item_id',          value: item_id_dom.val()        },
291               { name: 'old_unit',         value: oldval                   },
292               { name: 'sellprice_dom_id', value: sellprice_dom.attr('id') });
293
294     $.post("controller.pl", data, kivi.eval_json_result);
295   };
296
297   ns.update_sellprice = function(item_id, price_str) {
298     var row       = $('#item_' + item_id).parents("tbody").first();
299     var price_elt = $(row).find('[name="reclamation.reclamation_items[].sellprice_as_number"]');
300     var html_elt  = $(row).find('[name="sellprice_text"]');
301     price_elt.val(price_str);
302     html_elt.html(price_str);
303   };
304
305   ns.load_second_row = function(row) {
306     var item_id_dom = $(row).find('[name="reclamation_item_ids[+]"]');
307     var div_elt     = $(row).find('[name="second_row"]');
308
309     if ($(div_elt).data('loaded') == 1) {
310       return;
311     }
312     var data = $('#reclamation_form').serializeArray();
313     data.push({ name: 'action',     value: 'Reclamation/load_second_rows' },
314               { name: 'item_ids[]', value: item_id_dom.val()        });
315
316     $.post("controller.pl", data, kivi.eval_json_result);
317   };
318
319   ns.load_all_second_rows = function() {
320     var rows = $('.row_entry').filter(function(idx, elt) {
321       return $(elt).find('[name="second_row"]').data('loaded') != 1;
322     });
323
324     var item_ids = $.map(rows, function(elt) {
325       var item_id = $(elt).find('[name="reclamation_item_ids[+]"]').val();
326       return { name: 'item_ids[]', value: item_id };
327     });
328
329     if (item_ids.length == 0) {
330       return;
331     }
332
333     var data = $('#reclamation_form').serializeArray();
334     data.push({ name: 'action', value: 'Reclamation/load_second_rows' });
335     data = data.concat(item_ids);
336
337     $.post("controller.pl", data, kivi.eval_json_result);
338   };
339
340   ns.hide_second_row = function(row) {
341     $(row).children().not(':first').hide();
342     $(row).data('expanded', 0);
343     var elt = $(row).find('.expand');
344     elt.attr('src', "image/expand.svg");
345     elt.attr('alt', kivi.t8('Show details'));
346     elt.attr('title', kivi.t8('Show details'));
347   };
348
349   ns.show_second_row = function(row) {
350     $(row).children().not(':first').show();
351     $(row).data('expanded', 1);
352     var elt = $(row).find('.expand');
353     elt.attr('src', "image/collapse.svg");
354     elt.attr('alt', kivi.t8('Hide details'));
355     elt.attr('title', kivi.t8('Hide details'));
356   };
357
358   ns.toggle_second_row = function(row) {
359     if ($(row).data('expanded') == 1) {
360       ns.hide_second_row(row);
361     } else {
362       ns.show_second_row(row);
363     }
364   };
365
366   ns.init_row_handlers = function() {
367     kivi.run_once_for('.recalc', 'on_change_recalc', function(elt) {
368       $(elt).change(ns.recalc_amounts_and_taxes);
369     });
370
371     kivi.run_once_for('.reformat_number', 'on_change_reformat', function(elt) {
372       $(elt).change(ns.reformat_number);
373     });
374
375     kivi.run_once_for('.unitselect', 'on_change_unit_with_oldval', function(elt) {
376       $(elt).data('oldval', $(elt).val());
377       $(elt).change(ns.unit_change);
378     });
379
380     kivi.run_once_for('.row_entry', 'on_kbd_click_show_hide', function(elt) {
381       $(elt).keydown(function(event) {
382         var row;
383         if (event.keyCode == 40 && event.shiftKey === true) {
384           // shift arrow down
385           event.preventDefault();
386           row = $(event.target).parents(".row_entry").first();
387           ns.load_second_row(row);
388           ns.show_second_row(row);
389           return false;
390         }
391         if (event.keyCode == 38 && event.shiftKey === true) {
392           // shift arrow up
393           event.preventDefault();
394           row = $(event.target).parents(".row_entry").first();
395           ns.hide_second_row(row);
396           return false;
397         }
398       });
399     });
400
401     kivi.run_once_for('.expand', 'expand_second_row', function(elt) {
402       $(elt).click(function(event) {
403         event.preventDefault();
404         var row = $(event.target).parents(".row_entry").first();
405         ns.load_second_row(row);
406         ns.toggle_second_row(row);
407         return false;
408       })
409     });
410
411   };
412
413   ns.redisplay_line_values = function(is_sales, data) {
414     $('.row_entry').each(function(idx, elt) {
415       $(elt).find('[name="linetotal"]').html(data[idx][0]);
416       if (is_sales && $(elt).find('[name="second_row"]').data('loaded') == 1) {
417         var mt = data[idx][1];
418         var mp = data[idx][2];
419         var h  = '<span';
420         if (mt[0] === '-') h += ' class="plus0"';
421         h += '>' + mt + '&nbsp;&nbsp;' + mp + '%';
422         h += '</span>';
423         $(elt).find('[name="linemargin"]').html(h);
424       }
425     });
426   };
427
428   ns.redisplay_cvpartnumbers = function(data) {
429     $('.row_entry').each(function(idx, elt) {
430       $(elt).find('[name="cvpartnumber"]').html(data[idx][0]);
431     });
432   };
433
434   ns.renumber_positions = function() {
435     $('.row_entry [name="position"]').each(function(idx, elt) {
436       $(elt).html(idx+1);
437     });
438     $('.row_entry').each(function(idx, elt) {
439       $(elt).data("position", idx+1);
440     });
441   };
442
443   ns.reorder_items = function(order_by) {
444     var dir = $('#' + order_by + '_header_id a img').attr("data-sort-dir");
445     $('#row_table_id thead a img').remove();
446
447     var src;
448     if (dir == "1") {
449       dir = "0";
450       src = "image/up.png";
451     } else {
452       dir = "1";
453       src = "image/down.png";
454     }
455
456     $('#' + order_by + '_header_id a').append('<img border=0 data-sort-dir=' + dir + ' src=' + src + ' alt="' + kivi.t8('sort items') + '">');
457
458     var data = $('#reclamation_form').serializeArray();
459     data.push({ name: 'action',   value: 'Reclamation/reorder_items' },
460               { name: 'order_by', value: order_by              },
461               { name: 'sort_dir', value: dir                   });
462
463     $.post("controller.pl", data, kivi.eval_json_result);
464   };
465
466   ns.redisplay_items = function(data) {
467     var old_rows = $('.row_entry').detach();
468     var new_rows = [];
469     $(data).each(function(idx, elt) {
470       new_rows.push(old_rows[elt.old_pos - 1]);
471     });
472     $(new_rows).appendTo($('#row_table_id'));
473     ns.renumber_positions();
474   };
475
476   ns.get_insert_before_item_id = function(wanted_pos) {
477     if (wanted_pos === '') return;
478
479     var insert_before_item_id;
480     // selection by data does not seem to work if data is changed at runtime
481     // var elt = $('.row_entry [data-position="' + wanted_pos + '"]');
482     $('.row_entry').each(function(idx, elt) {
483       if ($(elt).data("position") == wanted_pos) {
484         insert_before_item_id = $(elt).find('[name="reclamation_item_ids[+]"]').val();
485         return false;
486       }
487     });
488
489     return insert_before_item_id;
490   };
491
492   ns.add_item = function() {
493     if ($('#add_item_parts_id').val() === '') return;
494     if (!ns.check_cv()) return;
495
496     $('#row_table_id thead a img').remove();
497
498     var insert_before_item_id = ns.get_insert_before_item_id($('#add_item_position').val());
499
500     var data = $('#reclamation_form').serializeArray();
501     data.push({ name: 'action', value: 'Reclamation/add_item' },
502               { name: 'insert_before_item_id', value: insert_before_item_id });
503
504     $.post("controller.pl", data, kivi.eval_json_result);
505   };
506
507   ns.open_multi_items_dialog = function() {
508     if (!ns.check_cv()) return;
509
510     var pp = $("#add_item_parts_id").data("part_picker");
511     pp.o.multiple=1;
512     pp.open_dialog();
513   };
514
515   ns.add_multi_items = function(data) {
516     var insert_before_item_id = ns.get_insert_before_item_id($('#multi_items_position').val());
517     data = data.concat($('#reclamation_form').serializeArray());
518     data.push({ name: 'action', value: 'Reclamation/add_multi_items' },
519               { name: 'insert_before_item_id', value: insert_before_item_id });
520     $.post("controller.pl", data, kivi.eval_json_result);
521   };
522
523   ns.delete_reclamation_item_row = function(clicked) {
524     var row = $(clicked).parents("tbody").first();
525     $(row).remove();
526
527     ns.renumber_positions();
528     ns.recalc_amounts_and_taxes();
529   };
530
531   ns.row_table_scroll_down = function() {
532     $('#row_table_scroll_id').scrollTop($('#row_table_scroll_id')[0].scrollHeight);
533   };
534
535   ns.show_longdescription_dialog = function(clicked) {
536     var row                 = $(clicked).parents("tbody").first();
537     var position            = $(row).find('[name="position"]').html();
538     var partnumber          = $(row).find('[name="partnumber"]').html();
539     var description_elt     = $(row).find('[name="reclamation.reclamation_items[].description"]');
540     var longdescription_elt = $(row).find('[name="reclamation.reclamation_items[].longdescription"]');
541
542     var params = {
543       runningnumber:           position,
544       partnumber:              partnumber,
545       description:             description_elt.val(),
546       default_longdescription: longdescription_elt.val(),
547       set_function:            function(val) {
548         longdescription_elt.val(val);
549       }
550     };
551
552     kivi.SalesPurchase.edit_longdescription_with_params(params);
553   };
554
555   ns.price_chooser_item_row = function(clicked) {
556     if (!ns.check_cv()) return;
557     var row         = $(clicked).parents("tbody").first();
558     var item_id_dom = $(row).find('[name="reclamation_item_ids[+]"]');
559
560     var data = $('#reclamation_form').serializeArray();
561     data.push({ name: 'action',  value: 'Reclamation/price_popup' },
562               { name: 'item_id', value: item_id_dom.val()   });
563
564     $.post("controller.pl", data, kivi.eval_json_result);
565   };
566
567   ns.update_price_source = function(item_id, source, descr, price_str, price_editable) {
568     var row        = $('#item_' + item_id).parents("tbody").first();
569     var source_elt = $(row).find('[name="reclamation.reclamation_items[].active_price_source"]');
570     var button_elt = $(row).find('[name="price_chooser_button"]');
571
572     button_elt.val(button_elt.val().replace(/.*\|/, descr + " |"));
573     source_elt.val(source);
574
575     var editable_div_elt     = $(row).find('[name="editable_price"]');
576     var not_editable_div_elt = $(row).find('[name="not_editable_price"]');
577     if (price_editable == 1 && source === '') {
578       // editable
579       $(editable_div_elt).show();
580       $(not_editable_div_elt).hide();
581       $(editable_div_elt).find(':input').prop("disabled", false);
582       $(not_editable_div_elt).find(':input').prop("disabled", true);
583     } else {
584       // not editable
585       $(editable_div_elt).hide();
586       $(not_editable_div_elt).show();
587       $(editable_div_elt).find(':input').prop("disabled", true);
588       $(not_editable_div_elt).find(':input').prop("disabled", false);
589     }
590
591     if (price_str) {
592       var price_elt = $(row).find('[name="reclamation.reclamation_items[].sellprice_as_number"]');
593       var html_elt  = $(row).find('[name="sellprice_text"]');
594       price_elt.val(price_str);
595       html_elt.html(price_str);
596       ns.recalc_amounts_and_taxes();
597     }
598
599     kivi.io.close_dialog();
600   };
601
602   ns.update_discount_source = function(item_id, source, descr, discount_str, price_editable) {
603     var row        = $('#item_' + item_id).parents("tbody").first();
604     var source_elt = $(row).find('[name="reclamation.reclamation_items[].active_discount_source"]');
605     var button_elt = $(row).find('[name="price_chooser_button"]');
606
607     button_elt.val(button_elt.val().replace(/\|.*/, "| " + descr));
608     source_elt.val(source);
609
610     var editable_div_elt     = $(row).find('[name="editable_discount"]');
611     var not_editable_div_elt = $(row).find('[name="not_editable_discount"]');
612     if (price_editable == 1 && source === '') {
613       // editable
614       $(editable_div_elt).show();
615       $(not_editable_div_elt).hide();
616       $(editable_div_elt).find(':input').prop("disabled", false);
617       $(not_editable_div_elt).find(':input').prop("disabled", true);
618     } else {
619       // not editable
620       $(editable_div_elt).hide();
621       $(not_editable_div_elt).show();
622       $(editable_div_elt).find(':input').prop("disabled", true);
623       $(not_editable_div_elt).find(':input').prop("disabled", false);
624     }
625
626     if (discount_str) {
627       var discount_elt = $(row).find('[name="reclamation.reclamation_items[].discount_as_percent"]');
628       var html_elt     = $(row).find('[name="discount_text"]');
629       discount_elt.val(discount_str);
630       html_elt.html(discount_str);
631       ns.recalc_amounts_and_taxes();
632     }
633
634     kivi.io.close_dialog();
635   };
636
637   ns.update_row_from_master_data = function(clicked) {
638     var row = $(clicked).parents("tbody").first();
639     var item_id_dom = $(row).find('[name="reclamation_item_ids[+]"]');
640
641     var data = $('#reclamation_form').serializeArray();
642     data.push({ name: 'action', value: 'Reclamation/update_row_from_master_data' });
643     data.push({ name: 'item_ids[]', value: item_id_dom.val() });
644
645     $.post("controller.pl", data, kivi.eval_json_result);
646   };
647
648   ns.update_all_rows_from_master_data = function() {
649     var item_ids = $.map($('.row_entry'), function(elt) {
650       var item_id = $(elt).find('[name="reclamation_item_ids[+]"]').val();
651       return { name: 'item_ids[]', value: item_id };
652     });
653
654     if (item_ids.length == 0) {
655       return;
656     }
657
658     var data = $('#reclamation_form').serializeArray();
659     data.push({ name: 'action', value: 'Reclamation/update_row_from_master_data' });
660     data = data.concat(item_ids);
661
662     $.post("controller.pl", data, kivi.eval_json_result);
663   };
664
665   ns.show_calculate_qty_dialog = function(clicked) {
666     var row        = $(clicked).parents("tbody").first();
667     var input_id   = $(row).find('[name="reclamation.reclamation_items[].qty_as_number"]').attr('id');
668     var formula_id = $(row).find('[name="formula[+]"]').attr('id');
669
670     calculate_qty_selection_dialog("", input_id, "", formula_id);
671     return true;
672   };
673
674   ns.edit_custom_shipto = function() {
675     if (!ns.check_cv()) return;
676
677     kivi.SalesPurchase.edit_custom_shipto();
678   };
679
680   ns.purchase_reclamation_check_for_direct_delivery = function(save_params) {
681     if ($('#type').val() != 'sales_reclamation') {
682       return alert(kivi.t8("Error: This is not a sales reclamation."));
683     }
684
685     var empty = true;
686     var shipto;
687     if ($('#reclamation_shipto_id').val() !== '') {
688       empty = false;
689       shipto = $('#reclamation_shipto_id option:selected').text();
690     } else {
691       $('#shipto_inputs [id^="shipto"]').each(function(_idx, elt) {
692         if (!empty)                                     return;
693         if (/^shipto_to_copy/.test($(elt).prop('id')))  return;
694         if (/^shiptocp_gender/.test($(elt).prop('id'))) return;
695         if (/^shiptocvar_/.test($(elt).prop('id')))     return;
696         if ($(elt).val() !== '') {
697           empty = false;
698           return;
699         }
700       });
701       var shipto_elements = [];
702       $([$('#shiptoname').val(), $('#shiptostreet').val(), $('#shiptozipcode').val(), $('#shiptocity').val()]).each(function(_idx, elt) {
703         if (elt !== '') shipto_elements.push(elt);
704       });
705       shipto = shipto_elements.join('; ');
706     }
707
708     if (!empty) {
709       ns.direct_delivery_dialog(shipto, save_params);
710     } else {
711       ns.save(save_params);
712     }
713   };
714
715   ns.direct_delivery_callback = function(accepted, save_params) {
716     $('#direct-delivery-dialog').dialog('close');
717
718     if (accepted) {
719       $('<input type="hidden" name="use_shipto">').appendTo('#reclamation_form').val('1');
720     }
721
722     ns.save(save_params);
723   };
724
725   ns.direct_delivery_dialog = function(shipto, save_params) {
726     $('#direct-delivery-dialog').remove();
727
728     var save_params_string = '{';
729     if (save_params) {
730       const action             = save_params.action;
731       const warn_on_duplicates = save_params.warn_on_duplicates;
732       const warn_on_reqdate    = save_params.warn_on_reqdate;
733       const form_params        = save_params.form_params;
734
735
736       console.log(form_params)
737       console.log(Array.isArray(form_params))
738       if (action)
739         save_params_string += `'action':'${action}',`;
740       if (warn_on_duplicates)
741         save_params_string += `'warn_on_duplicates':'${warn_on_duplicates}',`;
742       if (warn_on_reqdate)
743         save_params_string += `'warn_on_reqdate':'${warn_on_reqdate}',`;
744       if (Array.isArray(form_params)) {
745         save_params_string += 'form_params:['
746         form_params.forEach(function(item) {
747           save_params_string += `{'name':'${item.name}','value':'${item.value}'},`;
748         });
749         save_params_string += ']';
750       } else {
751         save_params_string += `'form_params':{'name':'${form_params.name}','value':'${form_params.value}'}`;
752       }
753     }
754     save_params_string += '}';
755
756     console.log(save_params_string);
757
758     var text1 = kivi.t8('You have entered or selected the following shipping address for this customer:');
759     var text2 = kivi.t8('Do you want to carry this shipping address over to the new purchase reclamation so that the vendor can deliver the goods directly to your customer?');
760     var html  = '<div id="direct-delivery-dialog"><p>' + text1 + '</p><p>' + shipto + '</p><p>' + text2 + '</p>';
761     html      = html + '<hr><p>';
762     html      = html + '<input type="button" value="' + kivi.t8('Yes') + '" size="30" onclick="kivi.Reclamation.direct_delivery_callback(true,' + save_params_string + ')">';
763     html      = html + '&nbsp;';
764     html      = html + '<input type="button" value="' + kivi.t8('No')  + '" size="30" onclick="kivi.Reclamation.direct_delivery_callback(false,' + save_params_string + ')">';
765     html      = html + '</p></div>';
766     $(html).hide().appendTo('#reclamation_form');
767
768     kivi.popup_dialog({id: 'direct-delivery-dialog',
769                        dialog: {title:  kivi.t8('Carry over shipping address'),
770                                 height: 300,
771                                 width:  500 }});
772   };
773
774   ns.follow_up_window = function() {
775     var id   = $('#id').val();
776     var type = $('#type').val();
777     var number_info = $('#reclamation_record_number').val();
778
779     var name_info = '';
780     if ($('#type').val() == 'sales_reclamation') {
781       name_info = $('#reclamation_customer_id_name').val();
782     } else if ($('#type').val() == 'purchase_reclamation') {
783       name_info = $('#reclamation_vendor_id_name').val();
784     }
785
786     var info = '';
787     if (number_info !== '') { info += ' (' + number_info + ')' }
788     if (name_info   !== '') { info += ' (' + name_info + ')' }
789
790     if (!$('#follow_up_rowcount').length) {
791       $('<input type="hidden" name="follow_up_rowcount"        id="follow_up_rowcount">').appendTo('#reclamation_form');
792       $('<input type="hidden" name="follow_up_trans_id_1"      id="follow_up_trans_id_1">').appendTo('#reclamation_form');
793       $('<input type="hidden" name="follow_up_trans_type_1"    id="follow_up_trans_type_1">').appendTo('#reclamation_form');
794       $('<input type="hidden" name="follow_up_trans_info_1"    id="follow_up_trans_info_1">').appendTo('#reclamation_form');
795       $('<input type="hidden" name="follow_up_trans_subject_1" id="follow_up_trans_subject_1">').appendTo('#reclamation_form');
796     }
797     $('#follow_up_rowcount').val(1);
798     $('#follow_up_trans_id_1').val(id);
799     $('#follow_up_trans_type_1').val(type);
800     $('#follow_up_trans_info_1').val(info);
801     $('#follow_up_trans_subject_1').val($('#reclamation_transaction_description').val());
802
803     follow_up_window();
804   };
805
806   ns.create_part = function() {
807     var data = $('#reclamation_form').serializeArray();
808     data.push({ name: 'action', value: 'Reclamation/create_part' });
809
810     $.post("controller.pl", data, kivi.eval_json_result);
811   };
812
813   ns.get_selected_rows = function() {
814     let selected_rows = [];
815     $('[name^="multi_id_"]').each( function() {
816       if (this.checked) {
817         selected_rows.push($(this).parents("tr").first());
818       }
819     });
820     return selected_rows;
821   }
822
823   ns.toggle_selected_rows = function() {
824     let selected_rows = [];
825     $('[name^="multi_id_"]').each( function() {
826       this.checked = !this.checked;
827     });
828     return selected_rows;
829   }
830
831   ns.delete_selected_rows = function() {
832     selected_rows = ns.get_selected_rows();
833     let row_count = selected_rows.length;
834     if (row_count == 0) {
835       alert(kivi.t8("No row selected."));
836       return;
837     }
838     if (!confirm(kivi.t8("Do you want delete #1 rows?", [row_count]))) {
839       return;
840     }
841     selected_rows.forEach(function(row) {
842       $(row.parents("tbody").first()).remove();
843     });
844     ns.renumber_positions();
845     ns.recalc_amounts_and_taxes();
846   };
847
848   ns.set_selected_to_value = function(value_name) {
849     let value = $('[name="' + value_name + '_for_selected"]').val();
850     let selected_rows = ns.get_selected_rows();
851     selected_rows.forEach(function(row) {
852       $(row).find(
853         '[name="reclamation.reclamation_items[].' + value_name  + '"]'
854       ).val(
855         value
856       );
857     });
858   };
859
860 });
861
862 $(function() {
863   if ($('#type').val() == 'sales_reclamation') {
864     $('#reclamation_customer_id').change(kivi.Reclamation.reload_cv_dependent_selections);
865   } else {
866     $('#reclamation_vendor_id').change(kivi.Reclamation.reload_cv_dependent_selections);
867   }
868
869   $('#reclamation_currency_id').change(kivi.Reclamation.update_exchangerate);
870   $('#reclamation_transdate_as_date').change(kivi.Reclamation.update_exchangerate);
871   $('#reclamation_exchangerate_as_null_number').change(kivi.Reclamation.exchangerate_changed);
872
873   if ($('#type').val() == 'sales_reclamation') {
874     $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_sellprice_as_number').val(kivi.format_amount(o.sellprice, -2)) });
875   } else {
876     $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_sellprice_as_number').val(kivi.format_amount(o.lastcost, -2)) });
877   }
878   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_description').val(o.description) });
879   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_unit').val(o.unit) });
880
881   $('.add_item_input').keydown(function(event) {
882     if (event.keyCode == 13) {
883       event.preventDefault();
884       kivi.Reclamation.add_item();
885       return false;
886     }
887   });
888
889   kivi.Reclamation.init_row_handlers();
890
891   $('#row_table_id').on('sortstop', function(event, ui) {
892     $('#row_table_id thead a img').remove();
893     kivi.Reclamation.renumber_positions();
894   });
895
896   $('#expand_all').on('click', function(event) {
897     event.preventDefault();
898     if ($('#expand_all').data('expanded') == 1) {
899       $('#expand_all').data('expanded', 0);
900       $('#expand_all').attr('src', 'image/expand.svg');
901       $('#expand_all').attr('alt', kivi.t8('Show all details'));
902       $('#expand_all').attr('title', kivi.t8('Show all details'));
903       $('.row_entry').each(function(idx, elt) {
904         kivi.Reclamation.hide_second_row(elt);
905       });
906     } else {
907       $('#expand_all').data('expanded', 1);
908       $('#expand_all').attr('src', "image/collapse.svg");
909       $('#expand_all').attr('alt', kivi.t8('Hide all details'));
910       $('#expand_all').attr('title', kivi.t8('Hide all details'));
911       kivi.Reclamation.load_all_second_rows();
912       $('.row_entry').each(function(idx, elt) {
913         kivi.Reclamation.show_second_row(elt);
914       });
915     }
916     return false;
917   });
918
919   $('#select_all').click( function() {
920     var checked = this.checked
921     $('[name^="multi_id_"]').each(function() {
922       this.checked =  checked;
923     });
924   });
925
926   $('.reformat_number_as_null_number').change(kivi.Reclamation.reformat_number_as_null_number);
927
928 });