epic-s6ts
[kivitendo-erp.git] / js / kivi.DeliveryOrder.js
1 namespace('kivi.DeliveryOrder', function(ns) {
2   ns.check_cv = function() {
3     if ($('#type').val() == 'sales_delivery_order') {
4       if ($('#order_customer_id').val() === '') {
5         alert(kivi.t8('Please select a customer.'));
6         return false;
7       }
8     } else  {
9       if ($('#order_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="order.orderitems[].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 ($('#order_reqdate_as_date').val() === '') {
41       alert(kivi.t8('Please select a delivery date.'));
42       return false;
43     } else {
44       return true;
45     }
46   };
47
48   ns.save = function(action, warn_on_duplicates, warn_on_reqdate) {
49     if (!ns.check_cv()) return;
50     if (warn_on_duplicates && !ns.check_duplicate_parts()) return;
51     if (warn_on_reqdate    && !ns.check_valid_reqdate())   return;
52
53     var data = $('#order_form').serializeArray();
54     data.push({ name: 'action', value: 'DeliveryOrder/' + action });
55
56     $.post("controller.pl", data, kivi.eval_json_result);
57   };
58
59   ns.delete_order = function() {
60     var data = $('#order_form').serializeArray();
61     data.push({ name: 'action', value: 'DeliveryOrder/delete' });
62
63     $.post("controller.pl", data, kivi.eval_json_result);
64   };
65
66   ns.show_print_options = function(warn_on_duplicates, warn_on_reqdate) {
67     if (!ns.check_cv()) return;
68     if (warn_on_duplicates && !ns.check_duplicate_parts(kivi.t8("Do you really want to print?"))) return;
69     if (warn_on_reqdate    && !ns.check_valid_reqdate())   return;
70
71     kivi.popup_dialog({
72       id: 'print_options',
73       dialog: {
74         title: kivi.t8('Print options'),
75         width:  800,
76         height: 300
77       }
78     });
79   };
80
81   ns.open_stock_in_out_dialog = function(clicked, in_out) {
82     var $row = $(clicked).parents("tbody").first();
83     var id = $row.find('[name="orderitem_ids[+]"]').val();
84     $row.uniqueId();
85
86     kivi.popup_dialog({
87       id: "stock_in_out_dialog",
88       url: "controller.pl?action=DeliveryOrder/stock_in_out_dialog",
89       data: {
90         id:            $("#id").val(),
91         type:          $("#type").val(),
92         parts_id:      $row.find("[name$=parts_id]").val(),
93         unit:          $row.find("[name$=unit]").val(),
94         qty_as_number: $row.find("[name$=qty_as_number]").val(),
95         stock:         $row.find("[name$=stock_info]").val(),
96         item_id:       id,
97         row:           $row.attr("id"),
98       },
99       dialog: { title: kivi.t8('Transfer stock') }
100     });
101   };
102
103   ns.save_updated_stock = function() {
104     // stock information is saved in DOM as a yaml dump.
105     // we don't want to do this in javascript so we do a tiny roundtrip to the backend
106
107     let data = [];
108     $("#stock-in-out-table tr.listrow").each((i,row) => {
109       let qty = kivi.parse_amount($(row).find(".data-qty").val());
110
111       if (qty === 0) return;
112
113       data.push({
114         qty:                           qty,
115         warehouse_id:                  $(row).find(".data-warehouse-id").val(),
116         bin_id:                        $(row).find(".data-bin-id").val(),
117         chargenumber:                  $(row).find(".data-chargenumber").val(),
118         bestbefore:                    $(row).find(".data-bestbefore").val(),
119         unit:                          $(row).find(".data-unit").val(),
120         delivery_order_items_stock_id: $(row).find(".data-stock-id").val(),
121       });
122     });
123
124     let row = $(".data-row").val();
125
126     $.post("controller.pl",
127       kivi.serialize({
128         action:     "DeliveryOrder/update_stock_information",
129         unit:       $("#" + row).find("[name$=unit]").val(),
130         stock_info: data,
131         row:        row
132       }),
133       (data) => {
134         $("#" + row + " .data-stock-info").val(data.stock_info);
135         $("#" + row + " .data-stock-qty").text(data.stock_qty)
136         $("#stock_in_out_dialog").dialog("close");
137       }
138     );
139   };
140
141   ns.print = function() {
142     $('#print_options').dialog('close');
143
144     var data = $('#order_form').serializeArray();
145     data = data.concat($('#print_options_form').serializeArray());
146     data.push({ name: 'action', value: 'DeliveryOrder/print' });
147
148     $.post("controller.pl", data, kivi.eval_json_result);
149   };
150
151   var email_dialog;
152
153   ns.setup_send_email_dialog = function() {
154     kivi.SalesPurchase.show_all_print_options_elements();
155     kivi.SalesPurchase.show_print_options_elements([ 'sendmode', 'media', 'copies', 'remove_draft' ], false);
156
157     $('#print_options_form table').first().remove().appendTo('#email_form_print_options');
158
159     var to_focus = $('#email_form_to').val() === '' ? 'to' : 'subject';
160     $('#email_form_' + to_focus).focus();
161   };
162
163   ns.finish_send_email_dialog = function() {
164     kivi.SalesPurchase.show_all_print_options_elements();
165
166     $('#email_form_print_options table').first().remove().prependTo('#print_options_form');
167     return true;
168   };
169
170   ns.show_email_dialog = function(html) {
171     var id            = 'send_email_dialog';
172     var dialog_params = {
173       id:     id,
174       width:  800,
175       height: 600,
176       title:  kivi.t8('Send email'),
177       modal:  true,
178       beforeClose: kivi.DeliveryOrder.finish_send_email_dialog,
179       close: function(event, ui) {
180         email_dialog.remove();
181       }
182     };
183
184     $('#' + id).remove();
185
186     email_dialog = $('<div style="display:none" id="' + id + '"></div>').appendTo('body');
187     email_dialog.html(html);
188     email_dialog.dialog(dialog_params);
189
190     kivi.DeliveryOrder.setup_send_email_dialog();
191
192     $('.cancel').click(ns.close_email_dialog);
193
194     return true;
195   };
196
197   ns.send_email = function() {
198     // push button only once -> slow response from mail server
199     ns.email_dialog_disable_send();
200
201     var data = $('#order_form').serializeArray();
202     data = data.concat($('[name^="email_form."]').serializeArray());
203     data = data.concat($('[name^="print_options."]').serializeArray());
204     data.push({ name: 'action', value: 'DeliveryOrder/send_email' });
205     $.post("controller.pl", data, kivi.eval_json_result);
206   };
207
208   ns.email_dialog_disable_send = function() {
209     // disable mail send event to prevent
210     // impatient users to send multiple times
211     $('#send_email').prop('disabled', true);
212   };
213
214   ns.close_email_dialog = function() {
215     email_dialog.dialog("close");
216   };
217
218   ns.set_number_in_title = function(elt) {
219     $('#nr_in_title').html($(elt).val());
220   };
221
222   ns.reload_cv_dependent_selections = function() {
223     $('#order_shipto_id').val('');
224     var data = $('#order_form').serializeArray();
225     data.push({ name: 'action', value: 'DeliveryOrder/customer_vendor_changed' });
226
227     $.post("controller.pl", data, kivi.eval_json_result);
228   };
229
230   ns.reformat_number = function(event) {
231     $(event.target).val(kivi.format_amount(kivi.parse_amount($(event.target).val()), -2));
232   };
233
234   ns.reformat_number_as_null_number = function(event) {
235     if ($(event.target).val() === '') {
236       return;
237     }
238     ns.reformat_number(event);
239   };
240
241   ns.update_exchangerate = function(event) {
242     if (!ns.check_cv()) {
243       $('#order_currency_id').val($('#old_currency_id').val());
244       return;
245     }
246
247     var rate_input = $('#order_exchangerate_as_null_number');
248     // unset exchangerate if currency changed
249     if ($('#order_currency_id').val() !== $('#old_currency_id').val()) {
250       rate_input.val('');
251     }
252
253     // only set exchangerate if unset
254     if (rate_input.val() !== '') {
255       return;
256     }
257
258     var data = $('#order_form').serializeArray();
259     data.push({ name: 'action', value: 'DeliveryOrder/update_exchangerate' });
260
261     $.ajax({
262       url: 'controller.pl',
263       data: data,
264       method: 'POST',
265       dataType: 'json',
266       success: function(data){
267         if (!data.is_standard) {
268           $('#currency_name').text(data.currency_name);
269           if (data.exchangerate) {
270             rate_input.val(data.exchangerate);
271           } else {
272             rate_input.val('');
273           }
274           $('#exchangerate_settings').show();
275         } else {
276           rate_input.val('');
277           $('#exchangerate_settings').hide();
278         }
279         if ($('#order_currency_id').val() != $('#old_currency_id').val() ||
280             !data.is_standard && data.exchangerate != $('#old_exchangerate').val()) {
281           kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
282         }
283         $('#old_currency_id').val($('#order_currency_id').val());
284         $('#old_exchangerate').val(data.exchangerate);
285       }
286     });
287   };
288
289   ns.exchangerate_changed = function(event) {
290     if (kivi.parse_amount($('#order_exchangerate_as_null_number').val()) != kivi.parse_amount($('#old_exchangerate').val())) {
291       kivi.display_flash('warning', kivi.t8('You have changed the currency or exchange rate. Please check prices.'));
292       $('#old_exchangerate').val($('#order_exchangerate_as_null_number').val());
293     }
294   };
295
296   ns.unit_change = function(event) {
297     var row           = $(event.target).parents("tbody").first();
298     var item_id_dom   = $(row).find('[name="orderitem_ids[+]"]');
299     var sellprice_dom = $(row).find('[name="order.orderitems[].sellprice_as_number"]');
300     var select_elt    = $(row).find('[name="order.orderitems[].unit"]');
301
302     var oldval = $(select_elt).data('oldval');
303     $(select_elt).data('oldval', $(select_elt).val());
304
305     var data = $('#order_form').serializeArray();
306     data.push({ name: 'action',           value: 'DeliveryOrder/unit_changed'     },
307               { name: 'item_id',          value: item_id_dom.val()        },
308               { name: 'old_unit',         value: oldval                   },
309               { name: 'sellprice_dom_id', value: sellprice_dom.attr('id') });
310
311     $.post("controller.pl", data, kivi.eval_json_result);
312   };
313
314   ns.update_sellprice = function(item_id, price_str) {
315     var row       = $('#item_' + item_id).parents("tbody").first();
316     var price_elt = $(row).find('[name="order.orderitems[].sellprice_as_number"]');
317     var html_elt  = $(row).find('[name="sellprice_text"]');
318     price_elt.val(price_str);
319     html_elt.html(price_str);
320   };
321
322   ns.load_second_row = function(row) {
323     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
324     var div_elt     = $(row).find('[name="second_row"]');
325
326     if ($(div_elt).data('loaded') == 1) {
327       return;
328     }
329     var data = $('#order_form').serializeArray();
330     data.push({ name: 'action',     value: 'DeliveryOrder/load_second_rows' },
331               { name: 'item_ids[]', value: item_id_dom.val()        });
332
333     $.post("controller.pl", data, kivi.eval_json_result);
334   };
335
336   ns.load_all_second_rows = function() {
337     var rows = $('.row_entry').filter(function(idx, elt) {
338       return $(elt).find('[name="second_row"]').data('loaded') != 1;
339     });
340
341     var item_ids = $.map(rows, function(elt) {
342       var item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
343       return { name: 'item_ids[]', value: item_id };
344     });
345
346     if (item_ids.length == 0) {
347       return;
348     }
349
350     var data = $('#order_form').serializeArray();
351     data.push({ name: 'action', value: 'DeliveryOrder/load_second_rows' });
352     data = data.concat(item_ids);
353
354     $.post("controller.pl", data, kivi.eval_json_result);
355   };
356
357   ns.hide_second_row = function(row) {
358     $(row).children().not(':first').hide();
359     $(row).data('expanded', 0);
360     var elt = $(row).find('.expand');
361     elt.attr('src', "image/expand.svg");
362     elt.attr('alt', kivi.t8('Show details'));
363     elt.attr('title', kivi.t8('Show details'));
364   };
365
366   ns.show_second_row = function(row) {
367     $(row).children().not(':first').show();
368     $(row).data('expanded', 1);
369     var elt = $(row).find('.expand');
370     elt.attr('src', "image/collapse.svg");
371     elt.attr('alt', kivi.t8('Hide details'));
372     elt.attr('title', kivi.t8('Hide details'));
373   };
374
375   ns.toggle_second_row = function(row) {
376     if ($(row).data('expanded') == 1) {
377       ns.hide_second_row(row);
378     } else {
379       ns.show_second_row(row);
380     }
381   };
382
383   ns.init_row_handlers = function() {
384     kivi.run_once_for('.reformat_number', 'on_change_reformat', function(elt) {
385       $(elt).change(ns.reformat_number);
386     });
387
388     kivi.run_once_for('.unitselect', 'on_change_unit_with_oldval', function(elt) {
389       $(elt).data('oldval', $(elt).val());
390       $(elt).change(ns.unit_change);
391     });
392
393     kivi.run_once_for('.row_entry', 'on_kbd_click_show_hide', function(elt) {
394       $(elt).keydown(function(event) {
395         var row;
396         if (event.keyCode == 40 && event.shiftKey === true) {
397           // shift arrow down
398           event.preventDefault();
399           row = $(event.target).parents(".row_entry").first();
400           ns.load_second_row(row);
401           ns.show_second_row(row);
402           return false;
403         }
404         if (event.keyCode == 38 && event.shiftKey === true) {
405           // shift arrow up
406           event.preventDefault();
407           row = $(event.target).parents(".row_entry").first();
408           ns.hide_second_row(row);
409           return false;
410         }
411       });
412     });
413
414     kivi.run_once_for('.expand', 'expand_second_row', function(elt) {
415       $(elt).click(function(event) {
416         event.preventDefault();
417         var row = $(event.target).parents(".row_entry").first();
418         ns.load_second_row(row);
419         ns.toggle_second_row(row);
420         return false;
421       })
422     });
423
424   };
425
426   ns.redisplay_line_values = function(is_sales, data) {
427     $('.row_entry').each(function(idx, elt) {
428       $(elt).find('[name="linetotal"]').html(data[idx][0]);
429       if (is_sales && $(elt).find('[name="second_row"]').data('loaded') == 1) {
430         var mt = data[idx][1];
431         var mp = data[idx][2];
432         var h  = '<span';
433         if (mt[0] === '-') h += ' class="plus0"';
434         h += '>' + mt + '&nbsp;&nbsp;' + mp + '%';
435         h += '</span>';
436         $(elt).find('[name="linemargin"]').html(h);
437       }
438     });
439   };
440
441   ns.redisplay_cvpartnumbers = function(data) {
442     $('.row_entry').each(function(idx, elt) {
443       $(elt).find('[name="cvpartnumber"]').html(data[idx][0]);
444     });
445   };
446
447   ns.renumber_positions = function() {
448     $('.row_entry [name="position"]').each(function(idx, elt) {
449       $(elt).html(idx+1);
450     });
451     $('.row_entry').each(function(idx, elt) {
452       $(elt).data("position", idx+1);
453     });
454   };
455
456   ns.reorder_items = function(order_by) {
457     var dir = $('#' + order_by + '_header_id a img').attr("data-sort-dir");
458     $('#row_table_id thead a img').remove();
459
460     var src;
461     if (dir == "1") {
462       dir = "0";
463       src = "image/up.png";
464     } else {
465       dir = "1";
466       src = "image/down.png";
467     }
468
469     $('#' + order_by + '_header_id a').append('<img border=0 data-sort-dir=' + dir + ' src=' + src + ' alt="' + kivi.t8('sort items') + '">');
470
471     var data = $('#order_form').serializeArray();
472     data.push({ name: 'action',   value: 'DeliveryOrder/reorder_items' },
473               { name: 'order_by', value: order_by              },
474               { name: 'sort_dir', value: dir                   });
475
476     $.post("controller.pl", data, kivi.eval_json_result);
477   };
478
479   ns.redisplay_items = function(data) {
480     var old_rows = $('.row_entry').detach();
481     var new_rows = [];
482     $(data).each(function(idx, elt) {
483       new_rows.push(old_rows[elt.old_pos - 1]);
484     });
485     $(new_rows).appendTo($('#row_table_id'));
486     ns.renumber_positions();
487   };
488
489   ns.get_insert_before_item_id = function(wanted_pos) {
490     if (wanted_pos === '') return;
491
492     var insert_before_item_id;
493     // selection by data does not seem to work if data is changed at runtime
494     // var elt = $('.row_entry [data-position="' + wanted_pos + '"]');
495     $('.row_entry').each(function(idx, elt) {
496       if ($(elt).data("position") == wanted_pos) {
497         insert_before_item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
498         return false;
499       }
500     });
501
502     return insert_before_item_id;
503   };
504
505   ns.add_item = function() {
506     if ($('#add_item_parts_id').val() === '') return;
507     if (!ns.check_cv()) return;
508
509     $('#row_table_id thead a img').remove();
510
511     var insert_before_item_id = ns.get_insert_before_item_id($('#add_item_position').val());
512
513     var data = $('#order_form').serializeArray();
514     data.push({ name: 'action', value: 'DeliveryOrder/add_item' },
515               { name: 'insert_before_item_id', value: insert_before_item_id });
516
517     $.post("controller.pl", data, kivi.eval_json_result);
518   };
519
520   ns.open_multi_items_dialog = function() {
521     if (!ns.check_cv()) return;
522
523     var pp = $("#add_item_parts_id").data("part_picker");
524     pp.o.multiple=1;
525     pp.open_dialog();
526   };
527
528   ns.add_multi_items = function(data) {
529     var insert_before_item_id = ns.get_insert_before_item_id($('#multi_items_position').val());
530     data = data.concat($('#order_form').serializeArray());
531     data.push({ name: 'action', value: 'DeliveryOrder/add_multi_items' },
532               { name: 'insert_before_item_id', value: insert_before_item_id });
533     $.post("controller.pl", data, kivi.eval_json_result);
534   };
535
536   ns.delete_order_item_row = function(clicked) {
537     var row = $(clicked).parents("tbody").first();
538     $(row).remove();
539
540     ns.renumber_positions();
541   };
542
543   ns.row_table_scroll_down = function() {
544     $('#row_table_scroll_id').scrollTop($('#row_table_scroll_id')[0].scrollHeight);
545   };
546
547   ns.show_longdescription_dialog = function(clicked) {
548     var row                 = $(clicked).parents("tbody").first();
549     var position            = $(row).find('[name="position"]').html();
550     var partnumber          = $(row).find('[name="partnumber"]').html();
551     var description_elt     = $(row).find('[name="order.orderitems[].description"]');
552     var longdescription_elt = $(row).find('[name="order.orderitems[].longdescription"]');
553
554     var params = {
555       runningnumber:           position,
556       partnumber:              partnumber,
557       description:             description_elt.val(),
558       default_longdescription: longdescription_elt.val(),
559       set_function:            function(val) {
560         longdescription_elt.val(val);
561       }
562     };
563
564     kivi.SalesPurchase.edit_longdescription_with_params(params);
565   };
566
567   ns.price_chooser_item_row = function(clicked) {
568     if (!ns.check_cv()) return;
569     var row         = $(clicked).parents("tbody").first();
570     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
571
572     var data = $('#order_form').serializeArray();
573     data.push({ name: 'action',  value: 'DeliveryOrder/price_popup' },
574               { name: 'item_id', value: item_id_dom.val()   });
575
576     $.post("controller.pl", data, kivi.eval_json_result);
577   };
578
579   ns.show_vc_details_dialog = function() {
580     if (!ns.check_cv()) return;
581     var vc;
582     var vc_id;
583     var title;
584     if ($('#order_customer_id').val()) {
585       vc    = 'customer';
586       vc_id = $('#order_customer_id').val();
587       title = kivi.t8('Customer details');
588     } else {
589       vc    = 'vendor';
590       vc_id = $('#order_vendor_id').val();
591       title = kivi.t8('Vendor details');
592     }
593
594     kivi.popup_dialog({
595       url:    'controller.pl',
596       data:   { action: 'DeliveryOrder/show_customer_vendor_details_dialog',
597                 type  : $('#type').val(),
598                 vc    : vc,
599                 vc_id : vc_id
600               },
601       id:     'jq_customer_vendor_details_dialog',
602       dialog: {
603         title:  title,
604         width:  800,
605         height: 650
606       }
607     });
608     return true;
609   };
610
611   ns.update_row_from_master_data = function(clicked) {
612     var row = $(clicked).parents("tbody").first();
613     var item_id_dom = $(row).find('[name="orderitem_ids[+]"]');
614
615     var data = $('#order_form').serializeArray();
616     data.push({ name: 'action', value: 'DeliveryOrder/update_row_from_master_data' });
617     data.push({ name: 'item_ids[]', value: item_id_dom.val() });
618
619     $.post("controller.pl", data, kivi.eval_json_result);
620   };
621
622   ns.update_all_rows_from_master_data = function() {
623     var item_ids = $.map($('.row_entry'), function(elt) {
624       var item_id = $(elt).find('[name="orderitem_ids[+]"]').val();
625       return { name: 'item_ids[]', value: item_id };
626     });
627
628     if (item_ids.length == 0) {
629       return;
630     }
631
632     var data = $('#order_form').serializeArray();
633     data.push({ name: 'action', value: 'DeliveryOrder/update_row_from_master_data' });
634     data = data.concat(item_ids);
635
636     $.post("controller.pl", data, kivi.eval_json_result);
637   };
638
639   ns.show_calculate_qty_dialog = function(clicked) {
640     var row        = $(clicked).parents("tbody").first();
641     var input_id   = $(row).find('[name="order.orderitems[].qty_as_number"]').attr('id');
642     var formula_id = $(row).find('[name="formula[+]"]').attr('id');
643
644     calculate_qty_selection_dialog("", input_id, "", formula_id);
645     return true;
646   };
647
648   ns.edit_custom_shipto = function() {
649     if (!ns.check_cv()) return;
650
651     kivi.SalesPurchase.edit_custom_shipto();
652   };
653
654   ns.purchase_order_check_for_direct_delivery = function() {
655     if ($('#type').val() != 'sales_order') {
656       kivi.submit_form_with_action($('#order_form'), 'DeliveryOrder/purchase_order');
657     }
658
659     var empty = true;
660     var shipto;
661     if ($('#order_shipto_id').val() !== '') {
662       empty = false;
663       shipto = $('#order_shipto_id option:selected').text();
664     } else {
665       $('#shipto_inputs [id^="shipto"]').each(function(idx, elt) {
666         if (!empty)                                     return true;
667         if (/^shipto_to_copy/.test($(elt).prop('id')))  return true;
668         if (/^shiptocp_gender/.test($(elt).prop('id'))) return true;
669         if (/^shiptocvar_/.test($(elt).prop('id')))     return true;
670         if ($(elt).val() !== '') {
671           empty = false;
672           return false;
673         }
674       });
675       var shipto_elements = [];
676       $([$('#shiptoname').val(), $('#shiptostreet').val(), $('#shiptozipcode').val(), $('#shiptocity').val()]).each(function(idx, elt) {
677         if (elt !== '') shipto_elements.push(elt);
678       });
679       shipto = shipto_elements.join('; ');
680     }
681
682     var use_it = false;
683     if (!empty) {
684       ns.direct_delivery_dialog(shipto);
685     } else {
686       kivi.submit_form_with_action($('#order_form'), 'DeliveryOrder/purchase_order');
687     }
688   };
689
690   ns.direct_delivery_callback = function(accepted) {
691     $('#direct-delivery-dialog').dialog('close');
692
693     if (accepted) {
694       $('<input type="hidden" name="use_shipto">').appendTo('#order_form').val('1');
695     }
696
697     kivi.submit_form_with_action($('#order_form'), 'DeliveryOrder/purchase_order');
698   };
699
700   ns.direct_delivery_dialog = function(shipto) {
701     $('#direct-delivery-dialog').remove();
702
703     var text1 = kivi.t8('You have entered or selected the following shipping address for this customer:');
704     var text2 = kivi.t8('Do you want to carry this shipping address over to the new purchase order so that the vendor can deliver the goods directly to your customer?');
705     var html  = '<div id="direct-delivery-dialog"><p>' + text1 + '</p><p>' + shipto + '</p><p>' + text2 + '</p>';
706     html      = html + '<hr><p>';
707     html      = html + '<input type="button" value="' + kivi.t8('Yes') + '" size="30" onclick="kivi.DeliveryOrder.direct_delivery_callback(true)">';
708     html      = html + '&nbsp;';
709     html      = html + '<input type="button" value="' + kivi.t8('No')  + '" size="30" onclick="kivi.DeliveryOrder.direct_delivery_callback(false)">';
710     html      = html + '</p></div>';
711     $(html).hide().appendTo('#order_form');
712
713     kivi.popup_dialog({id: 'direct-delivery-dialog',
714                        dialog: {title:  kivi.t8('Carry over shipping address'),
715                                 height: 300,
716                                 width:  500 }});
717   };
718
719   ns.follow_up_window = function() {
720     var id   = $('#id').val();
721     var type = $('#type').val();
722
723     var number_info = '';
724     if ($('#type').val() == 'sales_order' || $('#type').val() == 'purchase_order') {
725       number_info = $('#order_ordnumber').val();
726     } else if ($('#type').val() == 'sales_quotation' || $('#type').val() == 'request_quotation') {
727       number_info = $('#order_quonumber').val();
728     }
729
730     var name_info = '';
731     if ($('#type').val() == 'sales_order' || $('#type').val() == 'sales_quotation') {
732       name_info = $('#order_customer_id_name').val();
733     } else if ($('#type').val() == 'purchase_order' || $('#type').val() == 'request_quotation') {
734       name_info = $('#order_vendor_id_name').val();
735     }
736
737     var info = '';
738     if (number_info !== '') { info += ' (' + number_info + ')' }
739     if (name_info   !== '') { info += ' (' + name_info + ')' }
740
741     if (!$('#follow_up_rowcount').lenght) {
742       $('<input type="hidden" name="follow_up_rowcount"        id="follow_up_rowcount">').appendTo('#order_form');
743       $('<input type="hidden" name="follow_up_trans_id_1"      id="follow_up_trans_id_1">').appendTo('#order_form');
744       $('<input type="hidden" name="follow_up_trans_type_1"    id="follow_up_trans_type_1">').appendTo('#order_form');
745       $('<input type="hidden" name="follow_up_trans_info_1"    id="follow_up_trans_info_1">').appendTo('#order_form');
746       $('<input type="hidden" name="follow_up_trans_subject_1" id="follow_up_trans_subject_1">').appendTo('#order_form');
747     }
748     $('#follow_up_rowcount').val(1);
749     $('#follow_up_trans_id_1').val(id);
750     $('#follow_up_trans_type_1').val(type);
751     $('#follow_up_trans_info_1').val(info);
752     $('#follow_up_trans_subject_1').val($('#order_transaction_description').val());
753
754     follow_up_window();
755   };
756
757   ns.create_part = function() {
758     var data = $('#order_form').serializeArray();
759     data.push({ name: 'action', value: 'DeliveryOrder/create_part' });
760
761     $.post("controller.pl", data, kivi.eval_json_result);
762   };
763
764 });
765
766 $(function() {
767   $('#order_customer_id').change(kivi.DeliveryOrder.reload_cv_dependent_selections);
768   $('#order_vendor_id').change(kivi.DeliveryOrder.reload_cv_dependent_selections);
769
770   $('#order_currency_id').change(kivi.DeliveryOrder.update_exchangerate);
771   $('#order_transdate_as_date').change(kivi.DeliveryOrder.update_exchangerate);
772   $('#order_exchangerate_as_null_number').change(kivi.DeliveryOrder.exchangerate_changed);
773
774   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_description').val(o.description) });
775   $('#add_item_parts_id').on('set_item:PartPicker', function(e,o) { $('#add_item_unit').val(o.unit) });
776
777   $('.add_item_input').keydown(function(event) {
778     if (event.keyCode == 13) {
779       event.preventDefault();
780       kivi.DeliveryOrder.add_item();
781       return false;
782     }
783   });
784
785   kivi.DeliveryOrder.init_row_handlers();
786
787   $('#row_table_id').on('sortstop', function(event, ui) {
788     $('#row_table_id thead a img').remove();
789     kivi.DeliveryOrder.renumber_positions();
790   });
791
792   $('#expand_all').on('click', function(event) {
793     event.preventDefault();
794     if ($('#expand_all').data('expanded') == 1) {
795       $('#expand_all').data('expanded', 0);
796       $('#expand_all').attr('src', 'image/expand.svg');
797       $('#expand_all').attr('alt', kivi.t8('Show all details'));
798       $('#expand_all').attr('title', kivi.t8('Show all details'));
799       $('.row_entry').each(function(idx, elt) {
800         kivi.DeliveryOrder.hide_second_row(elt);
801       });
802     } else {
803       $('#expand_all').data('expanded', 1);
804       $('#expand_all').attr('src', "image/collapse.svg");
805       $('#expand_all').attr('alt', kivi.t8('Hide all details'));
806       $('#expand_all').attr('title', kivi.t8('Hide all details'));
807       kivi.DeliveryOrder.load_all_second_rows();
808       $('.row_entry').each(function(idx, elt) {
809         kivi.DeliveryOrder.show_second_row(elt);
810       });
811     }
812     return false;
813   });
814
815   $('.reformat_number_as_null_number').change(kivi.DeliveryOrder.reformat_number_as_null_number);
816
817 });