Zusätzliche Rechnungsadressen: in Verkaufsbelegmasken auswählbar
[kivitendo-erp.git] / bin / mozilla / do.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger, Accounting
9 # Copyright (c) 1998-2003
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Delivery orders
32 #======================================================================
33
34 use Carp;
35 use List::MoreUtils qw(uniq);
36 use List::Util qw(max sum);
37 use POSIX qw(strftime);
38
39 use SL::DB::DeliveryOrder;
40 use SL::DO;
41 use SL::IR;
42 use SL::IS;
43 use SL::MoreCommon qw(ary_diff restore_form save_form);
44 use SL::ReportGenerator;
45 use SL::WH;
46 use SL::YAML;
47 use Sort::Naturally ();
48 require "bin/mozilla/common.pl";
49 require "bin/mozilla/io.pl";
50 require "bin/mozilla/reportgenerator.pl";
51
52 use strict;
53
54 1;
55
56 # end of main
57
58 sub check_do_access {
59   $main::auth->assert($main::form->{type} . '_edit');
60 }
61
62 sub set_headings {
63   $main::lxdebug->enter_sub();
64
65   check_do_access();
66
67   my ($action) = @_;
68
69   my $form     = $main::form;
70   my $locale   = $main::locale;
71
72   if ($form->{type} eq 'purchase_delivery_order') {
73     $form->{vc}    = 'vendor';
74     $form->{title} = $action eq "edit" ? $locale->text('Edit Purchase Delivery Order') : $locale->text('Add Purchase Delivery Order');
75   } else {
76     $form->{vc}    = 'customer';
77     $form->{title} = $action eq "edit" ? $locale->text('Edit Sales Delivery Order') : $locale->text('Add Sales Delivery Order');
78   }
79
80   $form->{heading} = $locale->text('Delivery Order');
81
82   $main::lxdebug->leave_sub();
83 }
84
85 sub add {
86   $main::lxdebug->enter_sub();
87
88   check_do_access();
89
90   if (($::form->{type} =~ /purchase/) && !$::instance_conf->get_allow_new_purchase_invoice) {
91     $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
92   }
93
94   my $form     = $main::form;
95
96   set_headings("add");
97
98   $form->{show_details} = $::myconfig{show_form_details};
99   $form->{callback} = build_std_url('action=add', 'type', 'vc') unless ($form->{callback});
100
101   order_links(is_new => 1);
102   prepare_order();
103   display_form();
104
105   $main::lxdebug->leave_sub();
106 }
107
108 sub edit {
109   $main::lxdebug->enter_sub();
110
111   check_do_access();
112
113   my $form     = $main::form;
114
115   $form->{show_details} = $::myconfig{show_form_details};
116
117   # show history button
118   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
119   #/show hhistory button
120
121   $form->{simple_save} = 0;
122
123   set_headings("edit");
124
125   # editing without stuff to edit? try adding it first
126   if ($form->{rowcount} && !$form->{print_and_save}) {
127 #     map { $id++ if $form->{"multi_id_$_"} } (1 .. $form->{rowcount});
128 #     if (!$id) {
129
130       # reset rowcount
131       undef $form->{rowcount};
132       add();
133       $main::lxdebug->leave_sub();
134       return;
135 #     }
136   } elsif (!$form->{id}) {
137     add();
138     $main::lxdebug->leave_sub();
139     return;
140   }
141
142   my ($language_id, $printer_id);
143   if ($form->{print_and_save}) {
144     $form->{action}   = "dispatcher";
145     $form->{action_print} = "1";
146     $form->{resubmit} = 1;
147     $language_id      = $form->{language_id};
148     $printer_id       = $form->{printer_id};
149   }
150
151   set_headings("edit");
152
153   order_links();
154   prepare_order();
155
156   if ($form->{print_and_save}) {
157     $form->{language_id} = $language_id;
158     $form->{printer_id}  = $printer_id;
159   }
160
161   display_form();
162
163   $main::lxdebug->leave_sub();
164 }
165
166 sub order_links {
167   $main::lxdebug->enter_sub();
168
169   check_do_access();
170
171   my %params   = @_;
172   my $form     = $main::form;
173   my %myconfig = %main::myconfig;
174
175   # retrieve order/quotation
176   my $editing = $form->{id};
177
178   DO->retrieve('vc'  => $form->{vc},
179                'ids' => $form->{id});
180
181   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes delivery_term_id currency));
182
183   # get customer / vendor
184   if ($form->{vc} eq 'vendor') {
185     IR->get_vendor(\%myconfig, \%$form);
186     $form->{discount} = $form->{vendor_discount};
187   } else {
188     IS->get_customer(\%myconfig, \%$form);
189     $form->{discount} = $form->{customer_discount};
190     $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
191   }
192
193   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id delivery_term_id));
194   $form->restore_vars(qw(currency)) if ($form->{id} || $form->{convert_from_oe_ids});
195   $form->restore_vars(qw(taxincluded)) if $form->{id};
196   $form->restore_vars(qw(salesman_id)) if $editing;
197
198   $main::lxdebug->leave_sub();
199 }
200
201 sub prepare_order {
202   $main::lxdebug->enter_sub();
203
204   check_do_access();
205
206   my $form     = $main::form;
207   my %myconfig = %main::myconfig;
208
209   $form->{formname} = $form->{type} unless $form->{formname};
210
211   my $i = 0;
212   foreach my $ref (@{ $form->{form_details} }) {
213     $form->{rowcount} = ++$i;
214
215     map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
216   }
217   for my $i (1 .. $form->{rowcount}) {
218     if ($form->{id}) {
219       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
220     } else {
221       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"});
222     }
223     my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
224     $dec           = length $dec;
225     my $decimalplaces = ($dec > 2) ? $dec : 2;
226
227     # copy reqdate from deliverydate for invoice -> order conversion
228     $form->{"reqdate_$i"} = $form->{"deliverydate_$i"} unless $form->{"reqdate_$i"};
229
230     $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
231     $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
232
233     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
234     $dec_qty = length $dec_qty;
235     $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
236   }
237
238   $main::lxdebug->leave_sub();
239 }
240
241 sub setup_do_action_bar {
242   my @transfer_qty   = qw(kivi.SalesPurchase.delivery_order_check_transfer_qty);
243   my @req_trans_desc = qw(kivi.SalesPurchase.check_transaction_description) x!!$::instance_conf->get_require_transaction_description_ps;
244   my $is_customer    = $::form->{vc} eq 'customer';
245
246   my $undo_date  = DateTime->today->subtract(days => $::instance_conf->get_undo_transfer_interval);
247   my $insertdate = DateTime->from_kivitendo($::form->{insertdate});
248   my $undo_transfer  = 0;
249   if (ref $undo_date eq 'DateTime' && ref $insertdate eq 'DateTime') {
250     $undo_transfer = $insertdate > $undo_date;
251   }
252   for my $bar ($::request->layout->get('actionbar')) {
253     $bar->add(
254       action =>
255         [ t8('Update'),
256           submit    => [ '#form', { action => "update" } ],
257           id        => 'update_button',
258           accesskey => 'enter',
259         ],
260
261       combobox => [
262         action => [
263           t8('Save'),
264           submit   => [ '#form', { action => "save" } ],
265           checks   => [ 'kivi.validate_form' ],
266           disabled => $::form->{delivered} ? t8('This record has already been delivered.') : undef,
267         ],
268         action => [
269           t8('Save as new'),
270           submit   => [ '#form', { action => "save_as_new" } ],
271           checks   => [ 'kivi.validate_form' ],
272           disabled => !$::form->{id},
273         ],
274         action => [
275           t8('Mark as closed'),
276           submit   => [ '#form', { action => "mark_closed" } ],
277           checks   => [ 'kivi.validate_form' ],
278           confirm  => t8('This will remove the delivery order from showing as open even if contents are not delivered. Proceed?'),
279           disabled => !$::form->{id}    ? t8('This record has not been saved yet.')
280                     : $::form->{closed} ? t8('This record has already been closed.')
281                     :                     undef,
282         ],
283       ], # end of combobox "Save"
284
285       action => [
286         t8('Delete'),
287         submit   => [ '#form', { action => "delete" } ],
288         confirm  => t8('Do you really want to delete this object?'),
289         disabled => !$::form->{id}                                                                              ? t8('This record has not been saved yet.')
290                   : $::form->{delivered}                                                                        ? t8('This record has already been delivered.')
291                   : ($::form->{vc} eq 'customer' && !$::instance_conf->get_sales_delivery_order_show_delete)    ? t8('Deleting this type of record has been disabled in the configuration.')
292                   : ($::form->{vc} eq 'vendor'   && !$::instance_conf->get_purchase_delivery_order_show_delete) ? t8('Deleting this type of record has been disabled in the configuration.')
293                   :                                                                                               undef,
294       ],
295
296       combobox => [
297         action => [
298           t8('Transfer out'),
299           submit   => [ '#form', { action => "transfer_out" } ],
300           checks   => [ 'kivi.validate_form', @transfer_qty ],
301           disabled => $::form->{delivered} ? t8('This record has already been delivered.') : undef,
302           only_if  => $is_customer,
303         ],
304         action => [
305           t8('Transfer out via default'),
306           submit   => [ '#form', { action => "transfer_out_default" } ],
307           checks   => [ 'kivi.validate_form' ],
308           disabled => $::form->{delivered} ? t8('This record has already been delivered.') : undef,
309           only_if  => $is_customer && $::instance_conf->get_transfer_default,
310         ],
311         action => [
312           t8('Transfer in'),
313           submit   => [ '#form', { action => "transfer_in" } ],
314           checks   => [ 'kivi.validate_form', @transfer_qty ],
315           disabled => $::form->{delivered} ? t8('This record has already been delivered.') : undef,
316           only_if  => !$is_customer,
317         ],
318         action => [
319           t8('Transfer in via default'),
320           submit   => [ '#form', { action => "transfer_in_default" } ],
321           checks   => [ 'kivi.validate_form' ],
322           disabled => $::form->{delivered} ? t8('This record has already been delivered.') : undef,
323           only_if  => !$is_customer && $::instance_conf->get_transfer_default,
324         ],
325         action => [
326           t8('Undo Transfer'),
327           submit   => [ '#form', { action => "delete_transfers" } ],
328           checks   => [ 'kivi.validate_form' ],
329           only_if  => $::form->{delivered},
330           disabled => !$undo_transfer ? t8('Transfer date exceeds the maximum allowed interval.') : undef,
331         ],
332       ], # end of combobox "Transfer out"
333
334
335       'separator',
336
337       action => [
338         t8('Invoice'),
339         submit => [ '#form', { action => "invoice" } ],
340         disabled => !$::form->{id} ? t8('This record has not been saved yet.') : undef,
341         confirm  => $::form->{delivered}                                                                         ? undef
342                   : ($::form->{vc} eq 'customer' && $::instance_conf->get_sales_delivery_order_check_stocked)    ? t8('This record has not been stocked out. Proceed?')
343                   : ($::form->{vc} eq 'vendor'   && $::instance_conf->get_purchase_delivery_order_check_stocked) ? t8('This record has not been stocked in. Proceed?')
344                   :                                                                                                undef,
345       ],
346
347       combobox => [
348         action => [ t8('Export') ],
349         action => [
350           t8('Print'),
351           call   => [ 'kivi.SalesPurchase.show_print_dialog' ],
352           checks => [ 'kivi.validate_form' ],
353         ],
354         action => [
355           t8('E Mail'),
356           call   => [ 'kivi.SalesPurchase.show_email_dialog' ],
357           checks => [ 'kivi.validate_form' ],
358           disabled => !$::form->{id} ? t8('This record has not been saved yet.') : undef,
359         ],
360       ], # end of combobox "Export"
361
362       combobox =>  [
363         action => [ t8('more') ],
364         action => [
365           t8('History'),
366           call     => [ 'set_history_window', $::form->{id} * 1, 'id' ],
367           disabled => !$::form->{id} ? t8('This record has not been saved yet.') : undef,
368         ],
369         action => [
370           t8('Follow-Up'),
371           call     => [ 'follow_up_window' ],
372           disabled => !$::form->{id} ? t8('This record has not been saved yet.') : undef,
373         ],
374       ], # end if combobox "more"
375     );
376   }
377   $::request->layout->add_javascripts('kivi.Validator.js');
378 }
379
380 sub setup_do_search_action_bar {
381   my %params = @_;
382
383   for my $bar ($::request->layout->get('actionbar')) {
384     $bar->add(
385       action => [
386         t8('Search'),
387         submit    => [ '#form' ],
388         accesskey => 'enter',
389         checks    => [ 'kivi.validate_form' ],
390       ],
391     );
392   }
393   $::request->layout->add_javascripts('kivi.Validator.js');
394 }
395
396 sub setup_do_orders_action_bar {
397   my %params = @_;
398
399   for my $bar ($::request->layout->get('actionbar')) {
400     $bar->add(
401       action => [
402         t8('New invoice'),
403         submit    => [ '#form', { action => 'invoice_multi' } ],
404         checks    => [ [ 'kivi.check_if_entries_selected', '#form tbody input[type=checkbox]' ] ],
405         accesskey => 'enter',
406       ],
407       action => [
408         t8('Print'),
409         call   => [ 'kivi.SalesPurchase.show_print_dialog', 'js:kivi.MassDeliveryOrderPrint.submitMultiOrders' ],
410         checks => [ [ 'kivi.check_if_entries_selected', '#form tbody input[type=checkbox]' ] ],
411       ],
412     );
413   }
414 }
415
416 sub form_header {
417   $main::lxdebug->enter_sub();
418
419   check_do_access();
420
421   my $form     = $main::form;
422   my %myconfig = %main::myconfig;
423
424   my $class       = "SL::DB::" . ($form->{vc} eq 'customer' ? 'Customer' : 'Vendor');
425   $form->{VC_OBJ} = $class->load_cached($form->{ $form->{vc} . '_id' });
426
427   $form->{CONTACT_OBJ}   = $form->{cp_id} ? SL::DB::Contact->load_cached($form->{cp_id}) : undef;
428   my $current_employee   = SL::DB::Manager::Employee->current;
429   $form->{employee_id}   = $form->{old_employee_id} if $form->{old_employee_id};
430   $form->{salesman_id}   = $form->{old_salesman_id} if $form->{old_salesman_id};
431   $form->{employee_id} ||= $current_employee->id;
432   $form->{salesman_id} ||= $current_employee->id;
433
434   my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
435   $form->get_lists("price_factors"  => "ALL_PRICE_FACTORS",
436                    "business_types" => "ALL_BUSINESS_TYPES",
437     );
438   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
439   $form->{ALL_LANGUAGES}   = SL::DB::Manager::Language->get_all_sorted;
440
441   # Projects
442   my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
443   my @old_ids_cond    = @old_project_ids ? (id => \@old_project_ids) : ();
444   my @customer_cond;
445   if (($vc eq 'customers') && $::instance_conf->get_customer_projects_only_in_sales) {
446     @customer_cond = (
447       or => [
448         customer_id          => $::form->{customer_id},
449         billable_customer_id => $::form->{customer_id},
450       ]);
451   }
452   my @conditions = (
453     or => [
454       and => [ active => 1, @customer_cond ],
455       @old_ids_cond,
456     ]);
457
458   $::form->{ALL_PROJECTS}          = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
459   $::form->{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
460   $::form->{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
461   $::form->{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all_sorted(query => [
462     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
463   ]);
464   $::form->{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
465     or => [
466       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
467       and      => [
468         cp_cv_id => undef,
469         cp_id    => $::form->{cp_id} * 1
470       ]
471     ]
472   ]);
473
474   my $dispatch_to_popup = '';
475   if ($form->{resubmit} && ($form->{format} eq "html")) {
476     $dispatch_to_popup  = "window.open('about:blank','Beleg'); document.do.target = 'Beleg';";
477     $dispatch_to_popup .= "document.do.submit();";
478   } elsif ($form->{resubmit} && $form->{action_print}) {
479     # emulate click for resubmitting actions
480     $dispatch_to_popup  = "kivi.SalesPurchase.show_print_dialog(); kivi.SalesPurchase.print_record();";
481   }
482   $::request->{layout}->add_javascripts_inline("\$(function(){$dispatch_to_popup});");
483
484
485   $form->{follow_up_trans_info} = $form->{donumber} .'('. $form->{VC_OBJ}->name .')' if $form->{VC_OBJ};
486
487   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.File kivi.MassDeliveryOrderPrint kivi.SalesPurchase kivi.Part kivi.CustomerVendor kivi.Validator ckeditor/ckeditor ckeditor/adapters/jquery kivi.io));
488
489   setup_do_action_bar();
490
491   $form->header();
492   # Fix für Bug 1082 Erwartet wird: 'abteilungsNAME--abteilungsID'
493   # und Erweiterung für Bug 1760:
494   # Das war leider nur ein Teil-Fix, da das Verhalten den 'Erneuern'-Knopf
495   # nicht überlebt. Konsequent jetzt auf L umgestellt
496   #   $ perldoc SL::Template::Plugin::L
497   # Daher entsprechend nur die Anpassung in form_header
498   # und in DO.pm gemacht. 4 Testfälle:
499   # department_id speichern                 | i.O.
500   # department_id lesen                     | i.O.
501   # department leer überlebt erneuern       | i.O.
502   # department nicht leer überlebt erneuern | i.O.
503   # $main::lxdebug->message(0, 'ABTEILUNGS ID in form?' . $form->{department_id});
504   print $form->parse_html_template('do/form_header');
505
506   $main::lxdebug->leave_sub();
507 }
508
509 sub form_footer {
510   $main::lxdebug->enter_sub();
511
512   check_do_access();
513
514   my $form     = $main::form;
515
516   $form->{PRINT_OPTIONS}      = setup_sales_purchase_print_options();
517   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
518
519   my $shipto_cvars       = SL::DB::Shipto->new->cvars_by_config;
520   foreach my $var (@{ $shipto_cvars }) {
521     my $name = "shiptocvar_" . $var->config->name;
522     $var->value($form->{$name}) if exists $form->{$name};
523   }
524
525   print $form->parse_html_template('do/form_footer',
526     {transfer_default => ($::instance_conf->get_transfer_default),
527      shipto_cvars     => $shipto_cvars});
528
529   $main::lxdebug->leave_sub();
530 }
531
532 sub update_delivery_order {
533   $main::lxdebug->enter_sub();
534
535   check_do_access();
536
537   my $form     = $main::form;
538   my %myconfig = %main::myconfig;
539
540   set_headings($form->{"id"} ? "edit" : "add");
541
542   $form->{insertdate} = SL::DB::DeliveryOrder->new(id => $form->{id})->load->itime_as_date if $form->{id};
543
544   $form->{update} = 1;
545
546   my $payment_id;
547   $payment_id = $form->{payment_id} if $form->{payment_id};
548
549   my $vc = $form->{vc};
550   if (($form->{"previous_${vc}_id"} || $form->{"${vc}_id"}) != $form->{"${vc}_id"}) {
551     $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
552
553     if ($vc eq 'customer') {
554       IS->get_customer(\%myconfig, $form);
555       $::form->{billing_address_id} = $::form->{default_billing_address_id};
556     } else {
557       IR->get_vendor(\%myconfig, $form);
558     }
559   }
560
561   $form->{discount} =  $form->{"$form->{vc}_discount"} if defined $form->{"$form->{vc}_discount"};
562   # Problem: Wenn man ohne Erneuern einen Kunden/Lieferanten
563   # wechselt, wird der entsprechende Kunden/ Lieferantenrabatt
564   # nicht übernommen. Grundproblem: In Commit 82574e78
565   # hab ich aus discount customer_discount und vendor_discount
566   # gemacht und entsprechend an den Oberflächen richtig hin-
567   # geschoben. Die damals bessere Lösung wäre gewesen:
568   # In den Templates nur die hidden für form-discount wieder ein-
569   # setzen dann wäre die Verrenkung jetzt nicht notwendig.
570   # TODO: Ggf. Bugfix 1284, 1575 und 817 wieder zusammenführen
571   # Testfälle: Kunden mit Rabatt 0 -> Rabatt 20 i.O.
572   #            Kunde mit Rabatt 20 -> Rabatt 0  i.O.
573   #            Kunde mit Rabatt 20 -> Rabatt 5,5 i.O.
574   $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
575
576   my $i = $form->{rowcount};
577
578   if (   ($form->{"partnumber_$i"} eq "")
579       && ($form->{"description_$i"} eq "")
580       && ($form->{"partsgroup_$i"}  eq "")) {
581
582     check_form();
583
584   } else {
585
586     my $mode;
587     if ($form->{type} eq 'purchase_delivery_order') {
588       IR->retrieve_item(\%myconfig, $form);
589       $mode = 'IR';
590     } else {
591       IS->retrieve_item(\%myconfig, $form);
592       $mode = 'IS';
593     }
594
595     my $rows = scalar @{ $form->{item_list} };
596
597     if ($rows) {
598       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
599       if( !$form->{"qty_$i"} ) {
600         $form->{"qty_$i"} = 1;
601       }
602
603       if ($rows > 1) {
604
605         select_item(mode => $mode, pre_entered_qty => $form->{"qty_$i"});
606         $::dispatcher->end_request;
607
608       } else {
609
610         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
611
612         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
613
614         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
615
616         if ($sellprice) {
617           $form->{"sellprice_$i"} = $sellprice;
618         } else {
619           my $record        = _make_record();
620           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
621           my $best_price    = $price_source->best_price;
622           my $best_discount = $price_source->best_discount;
623
624           if ($best_price) {
625             $::form->{"sellprice_$i"}           = $best_price->price;
626             $::form->{"active_price_source_$i"} = $best_price->source;
627           }
628           if ($best_discount) {
629             $::form->{"discount_$i"}               = $best_discount->discount;
630             $::form->{"active_discount_source_$i"} = $best_discount->source;
631           }
632         }
633
634         $form->{"sellprice_$i"}          = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
635         $form->{"lastcost_$i"}           = $form->format_amount(\%myconfig, $form->{"lastcost_$i"});
636         $form->{"qty_$i"}                = $form->format_amount(\%myconfig, $form->{"qty_$i"});
637         $form->{"discount_$i"}           = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
638       }
639
640       display_form();
641
642     } else {
643
644       # ok, so this is a new part
645       # ask if it is a part or service item
646
647       if (   $form->{"partsgroup_$i"}
648           && ($form->{"partsnumber_$i"} eq "")
649           && ($form->{"description_$i"} eq "")) {
650         $form->{rowcount}--;
651         $form->{"discount_$i"} = "";
652         $form->{"not_discountable_$i"} = "";
653         display_form();
654
655       } else {
656         $form->{"id_$i"}   = 0;
657         new_item();
658       }
659     }
660   }
661
662   $main::lxdebug->leave_sub();
663 }
664
665 sub search {
666   $main::lxdebug->enter_sub();
667
668   check_do_access();
669
670   my $form     = $main::form;
671   my %myconfig = %main::myconfig;
672   my $locale   = $main::locale;
673
674   $form->{vc} = $form->{type} eq 'purchase_delivery_order' ? 'vendor' : 'customer';
675
676   $form->get_lists("projects"       => { "key" => "ALL_PROJECTS",
677                                          "all" => 1 },
678                    "business_types" => "ALL_BUSINESS_TYPES");
679   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
680   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
681   $form->{title}             = $locale->text('Delivery Orders');
682
683   setup_do_search_action_bar();
684
685   $form->header();
686
687   print $form->parse_html_template('do/search');
688
689   $main::lxdebug->leave_sub();
690 }
691
692 sub orders {
693   $main::lxdebug->enter_sub();
694
695   check_do_access();
696
697   my $form     = $main::form;
698   my %myconfig = %main::myconfig;
699   my $locale   = $main::locale;
700   my $cgi      = $::request->{cgi};
701
702   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.MassDeliveryOrderPrint kivi.SalesPurchase));
703   ($form->{ $form->{vc} }, $form->{"$form->{vc}_id"}) = split(/--/, $form->{ $form->{vc} });
704
705   report_generator_set_default_sort('transdate', 1);
706
707   DO->transactions();
708
709   $form->{rowcount} = scalar @{ $form->{DO} };
710
711   my @columns = qw(
712     ids                     transdate               reqdate
713     id                      donumber
714     ordnumber               customernumber          cusordnumber
715     name                    employee  salesman
716     shipvia                 globalprojectnumber
717     transaction_description department
718     open                    delivered
719     insertdate
720   );
721
722   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
723   $form->{l_delivered} = "Y"                     if ($form->{delivered} && $form->{notdelivered});
724
725   $form->{title}       = $locale->text('Delivery Orders');
726
727   my $attachment_basename = $form->{vc} eq 'vendor' ? $locale->text('purchase_delivery_order_list') : $locale->text('sales_delivery_order_list');
728
729   my $report = SL::ReportGenerator->new(\%myconfig, $form);
730
731   my @hidden_variables = map { "l_${_}" } @columns;
732   push @hidden_variables, $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered donumber ordnumber serialnumber cusordnumber
733                                           transaction_description transdatefrom transdateto reqdatefrom reqdateto
734                                           type vc employee_id salesman_id project_id parts_partnumber parts_description
735                                           insertdatefrom insertdateto business_id all department_id);
736
737   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
738
739   my %column_defs = (
740     'ids'                     => { raw_header_data => SL::Presenter::Tag::checkbox_tag("", id => "multi_all", checkall => "[data-checkall=1]"), align => 'center' },
741     'transdate'               => { 'text' => $locale->text('Delivery Order Date'), },
742     'reqdate'                 => { 'text' => $locale->text('Reqdate'), },
743     'id'                      => { 'text' => $locale->text('ID'), },
744     'donumber'                => { 'text' => $locale->text('Delivery Order'), },
745     'ordnumber'               => { 'text' => $locale->text('Order'), },
746     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
747     'cusordnumber'            => { 'text' => $locale->text('Customer Order Number'), },
748     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
749     'employee'                => { 'text' => $locale->text('Employee'), },
750     'salesman'                => { 'text' => $locale->text('Salesman'), },
751     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
752     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
753     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
754     'open'                    => { 'text' => $locale->text('Open'), },
755     'delivered'               => { 'text' => $locale->text('Delivered'), },
756     'department'              => { 'text' => $locale->text('Department'), },
757     'insertdate'              => { 'text' => $locale->text('Insert Date'), },
758   );
759
760   foreach my $name (qw(id transdate reqdate donumber ordnumber name employee salesman shipvia transaction_description department insertdate)) {
761     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
762     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
763   }
764
765   $form->{"l_type"} = "Y";
766   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
767
768   $column_defs{ids}->{visible} = 'HTML';
769
770   $report->set_columns(%column_defs);
771   $report->set_column_order(@columns);
772
773   $report->set_export_options('orders', @hidden_variables, qw(sort sortdir));
774
775   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
776
777   my @options;
778   if ($form->{customer}) {
779     push @options, $locale->text('Customer') . " : $form->{customer}";
780   }
781   if ($form->{vendor}) {
782     push @options, $locale->text('Vendor') . " : $form->{vendor}";
783   }
784   if ($form->{cp_name}) {
785     push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
786   }
787   if ($form->{department_id}) {
788     push @options, $locale->text('Department') . " : " . SL::DB::Department->new(id => $form->{department_id})->load->description;
789   }
790   if ($form->{donumber}) {
791     push @options, $locale->text('Delivery Order Number') . " : $form->{donumber}";
792   }
793   if ($form->{ordnumber}) {
794     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
795   }
796   push @options, $locale->text('Serial Number') . " : $form->{serialnumber}" if $form->{serialnumber};
797   if ($form->{business_id}) {
798     my $vc_type_label = $form->{vc} eq 'customer' ? $locale->text('Customer type') : $locale->text('Vendor type');
799     push @options, $vc_type_label . " : " . SL::DB::Business->new(id => $form->{business_id})->load->description;
800   }
801   if ($form->{transaction_description}) {
802     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
803   }
804   if ($form->{parts_description}) {
805     push @options, $locale->text('Part Description') . " : $form->{parts_description}";
806   }
807   if ($form->{parts_partnumber}) {
808     push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
809   }
810   if ( $form->{transdatefrom} or $form->{transdateto} ) {
811     push @options, $locale->text('Delivery Order Date');
812     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)     if $form->{transdatefrom};
813     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)     if $form->{transdateto};
814   };
815   if ( $form->{reqdatefrom} or $form->{reqdateto} ) {
816     push @options, $locale->text('Reqdate');
817     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{reqdatefrom}, 1)       if $form->{reqdatefrom};
818     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{reqdateto},   1)       if $form->{reqdateto};
819   };
820   if ( $form->{insertdatefrom} or $form->{insertdateto} ) {
821     push @options, $locale->text('Insert Date');
822     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{insertdatefrom}, 1)    if $form->{insertdatefrom};
823     push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{insertdateto},   1)    if $form->{insertdateto};
824   };
825   if ($form->{open}) {
826     push @options, $locale->text('Open');
827   }
828   if ($form->{closed}) {
829     push @options, $locale->text('Closed');
830   }
831   if ($form->{delivered}) {
832     push @options, $locale->text('Delivered');
833   }
834   if ($form->{notdelivered}) {
835     push @options, $locale->text('Not delivered');
836   }
837   push @options, $locale->text('Quick Search') . " : $form->{all}" if $form->{all};
838
839   my $pr = SL::DB::Manager::Printer->find_by(
840       printer_description => $::locale->text("sales_delivery_order_printer"));
841   if ($pr ) {
842       $form->{printer_id} = $pr->id;
843   }
844
845   my $print_options = SL::Helper::PrintOptions->get_print_options(
846     options => {
847       hide_language_id => 1,
848       show_bothsided   => 1,
849       show_headers     => 1,
850     },
851   );
852
853   $report->set_options('top_info_text'        => join("\n", @options),
854                        'raw_top_info_text'    => $form->parse_html_template('do/orders_top'),
855                        'raw_bottom_info_text' => $form->parse_html_template('do/orders_bottom', { print_options => $print_options }),
856                        'output_format'        => 'HTML',
857                        'title'                => $form->{title},
858                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
859     );
860   $report->set_options_from_form();
861   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
862
863   # add sort and escape callback, this one we use for the add sub
864   $form->{callback} = $href .= "&sort=$form->{sort}";
865
866   # escape callback for href
867   my $callback = $form->escape($href);
868
869   my $edit_url       = build_std_url('action=edit', 'type', 'vc');
870   my $edit_order_url = ($::instance_conf->get_feature_experimental_order)
871                      ? build_std_url('script=controller.pl', 'action=Order/edit', 'type=' . ($form->{type} eq 'sales_delivery_order' ? 'sales_order' : 'purchase_order'))
872                      : build_std_url('script=oe.pl',         'action=edit',       'type=' . ($form->{type} eq 'sales_delivery_order' ? 'sales_order' : 'purchase_order'));
873
874   my $idx            = 1;
875
876   foreach my $dord (@{ $form->{DO} }) {
877     $dord->{open}      = $dord->{closed}    ? $locale->text('No')  : $locale->text('Yes');
878     $dord->{delivered} = $dord->{delivered} ? $locale->text('Yes') : $locale->text('No');
879
880     my $row = { map { $_ => { 'data' => $dord->{$_} } } @columns };
881
882     my $ord_id = $dord->{id};
883     $row->{ids}  = {
884       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $ord_id)
885                     . $cgi->checkbox('-name' => "multi_id_${idx}",' id' => "multi_id_id_".$ord_id, '-value' => 1, 'data-checkall' => 1, '-label' => ''),
886       'valign'   => 'center',
887       'align'    => 'center',
888     };
889
890     $row->{donumber}->{link}  = $edit_url       . "&id=" . E($dord->{id})      . "&callback=${callback}";
891     $row->{ordnumber}->{link} = $edit_order_url . "&id=" . E($dord->{oe_id})   . "&callback=${callback}" if $dord->{oe_id};
892     $report->add_data($row);
893
894     $idx++;
895   }
896
897   setup_do_orders_action_bar();
898
899   $report->generate_with_headers();
900
901   $main::lxdebug->leave_sub();
902 }
903
904 sub save {
905   $main::lxdebug->enter_sub();
906
907   my (%params) = @_;
908
909   check_do_access();
910
911   my $form     = $main::form;
912   my %myconfig = %main::myconfig;
913   my $locale   = $main::locale;
914
915   $form->mtime_ischanged('delivery_orders');
916
917   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
918
919   $form->isblank("transdate", $locale->text('Delivery Order Date missing!'));
920
921   $form->{donumber} =~ s/^\s*//g;
922   $form->{donumber} =~ s/\s*$//g;
923
924   my $msg = ucfirst $form->{vc};
925   $form->isblank($form->{vc} . "_id", $locale->text($msg . " missing!"));
926
927   # $locale->text('Customer missing!');
928   # $locale->text('Vendor missing!');
929
930   remove_emptied_rows();
931   validate_items();
932
933   # check for serial number if part needs one
934   for my $i (1 .. $form->{rowcount} - 1) {
935     next unless $form->{"has_sernumber_$i"};
936     $form->isblank("serialnumber_$i",
937                    $locale->text('Serial Number missing in Row') . " $i");
938   }
939   # if the name changed get new values
940   my $vc = $form->{vc};
941   if (($form->{"previous_${vc}_id"} || $form->{"${vc}_id"}) != $form->{"${vc}_id"}) {
942     $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
943
944     if ($vc eq 'customer') {
945       IS->get_customer(\%myconfig, $form);
946       $::form->{billing_address_id} = $::form->{default_billing_address_id};
947     } else {
948       IR->get_vendor(\%myconfig, $form);
949     }
950
951     update();
952     $::dispatcher->end_request;
953   }
954
955   $form->{id} = 0 if $form->{saveasnew};
956   # we rely on converted_from_orderitems, if the workflow is used
957   # be sure that at least one position is linked to the original orderitem
958   if ($form->{convert_from_oe_ids}) {
959     my $has_linked_pos;
960     for my $i (1 .. $form->{rowcount}) {
961       if ($form->{"converted_from_orderitems_id_$i"}) {
962         $has_linked_pos = 1;
963         last;
964       }
965     }
966     if (!$has_linked_pos) {
967       $form->error($locale->text('Need at least one original position for the workflow Order to Delivery Order!'));
968     }
969   }
970   DO->save();
971   # saving the history
972   if(!exists $form->{addition}) {
973     $form->{snumbers} = qq|donumber_| . $form->{donumber};
974     $form->{addition} = "SAVED";
975     $form->save_history;
976   }
977   # /saving the history
978
979   $form->{simple_save} = 1;
980   if (!$params{no_redirect} && !$form->{print_and_save}) {
981     delete @{$form}{ary_diff([keys %{ $form }], [qw(login id script type cursor_fokus)])};
982     edit();
983     $::dispatcher->end_request;
984   }
985   $main::lxdebug->leave_sub();
986 }
987
988 sub delete {
989   $main::lxdebug->enter_sub();
990
991   check_do_access();
992
993   my $form     = $main::form;
994   my %myconfig = %main::myconfig;
995   my $locale   = $main::locale;
996   my $ret;
997   if ($ret = DO->delete()) {
998     # saving the history
999     if(!exists $form->{addition}) {
1000       $form->{snumbers} = qq|donumber_| . $form->{donumber};
1001       $form->{addition} = "DELETED";
1002       $form->save_history;
1003     }
1004     # /saving the history
1005
1006     $form->info($locale->text('Delivery Order deleted!'));
1007     $::dispatcher->end_request;
1008   }
1009
1010   $form->error($locale->text('Cannot delete delivery order!') . $ret);
1011
1012   $main::lxdebug->leave_sub();
1013 }
1014 sub delete_transfers {
1015   $main::lxdebug->enter_sub();
1016
1017   check_do_access();
1018
1019   my $form     = $main::form;
1020   my %myconfig = %main::myconfig;
1021   my $locale   = $main::locale;
1022   my $ret;
1023
1024   die "Invalid form type" unless $form->{type} =~ m/^(sales|purchase)_delivery_order$/;
1025
1026   if ($ret = DO->delete_transfers()) {
1027     # saving the history
1028     if(!exists $form->{addition}) {
1029       $form->{snumbers} = qq|donumber_| . $form->{donumber};
1030       $form->{addition} = "UNDO TRANSFER";
1031       $form->save_history;
1032     }
1033     # /saving the history
1034
1035     flash_later('info', $locale->text("Transfer undone."));
1036
1037     $form->{callback} = 'do.pl?action=edit&type=' . $form->{type} . '&id=' . $form->escape($form->{id});
1038     $form->redirect;
1039   }
1040
1041   $form->error($locale->text('Cannot undo delivery order transfer!') . $ret);
1042
1043   $main::lxdebug->leave_sub();
1044 }
1045
1046 sub invoice {
1047   $main::lxdebug->enter_sub();
1048
1049   my $form     = $main::form;
1050   my %myconfig = %main::myconfig;
1051   my $locale   = $main::locale;
1052
1053   check_do_access();
1054   $form->mtime_ischanged('delivery_orders');
1055
1056   $main::auth->assert($form->{type} eq 'purchase_delivery_order' ? 'vendor_invoice_edit' : 'invoice_edit');
1057
1058   $form->get_employee();
1059
1060   $form->{convert_from_do_ids} = $form->{id};
1061   # if we have a reqdate (Liefertermin), this is definetely the preferred
1062   # deliverydate for invoices
1063   $form->{deliverydate}        = $form->{reqdate} || $form->{transdate};
1064   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
1065   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1066   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
1067
1068   $form->{rowcount}--;
1069
1070   delete @{$form}{qw(id closed delivered)};
1071
1072   my ($script, $buysell);
1073   if ($form->{type} eq 'purchase_delivery_order') {
1074     $form->{title}  = $locale->text('Add Vendor Invoice');
1075     $form->{script} = 'ir.pl';
1076     $script         = "ir";
1077     $buysell        = 'sell';
1078
1079   } else {
1080     $form->{title}  = $locale->text('Add Sales Invoice');
1081     $form->{script} = 'is.pl';
1082     $script         = "is";
1083     $buysell        = 'buy';
1084   }
1085
1086   for my $i (1 .. $form->{rowcount}) {
1087     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"} } qw(ship qty sellprice lastcost basefactor discount);
1088     # für bug 1284
1089     # adds a customer/vendor discount, unless we have a workflow case
1090     # CAVEAT: has to be done, after the above parse_amount
1091     unless ($form->{"ordnumber"}) {
1092       if ($form->{discount}) { # Falls wir einen Lieferanten-/Kundenrabatt haben
1093         # und rabattfähig sind, dann
1094         unless ($form->{"not_discountable_$i"}) {
1095           $form->{"discount_$i"} = $form->{discount}*100; # ... nehmen wir diesen Rabatt
1096         }
1097       }
1098     }
1099     $form->{"donumber_$i"} = $form->{donumber};
1100     $form->{"converted_from_delivery_order_items_id_$i"} = delete $form->{"delivery_order_items_id_$i"};
1101   }
1102
1103   $form->{type} = "invoice";
1104
1105   # locale messages
1106   $main::locale = Locale->new("$myconfig{countrycode}", "$script");
1107   $locale = $main::locale;
1108
1109   require "bin/mozilla/$form->{script}";
1110
1111   my $currency = $form->{currency};
1112   invoice_links();
1113
1114   if ($form->{ordnumber}) {
1115     require SL::DB::Order;
1116     my $vc_id  = $form->{type} =~ /^sales/ ? 'customer_id' : 'vendor_id';
1117     if (my $order = SL::DB::Manager::Order->find_by(ordnumber => $form->{ordnumber}, $vc_id => $form->{"$vc_id"})) {
1118       $order->load;
1119       $form->{orddate} = $order->transdate_as_date;
1120       $form->{$_}      = $order->$_ for qw(payment_id salesman_id taxzone_id quonumber taxincluded);
1121       $form->{taxincluded_changed_by_user} = 1;
1122     }
1123   }
1124
1125   $form->{currency}     = $currency;
1126   $form->{exchangerate} = "";
1127   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, $buysell);
1128   $form->{exchangerate} = $form->{forex} if ($form->{forex});
1129
1130   prepare_invoice();
1131
1132   # format amounts
1133   for my $i (1 .. $form->{rowcount}) {
1134     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"});
1135
1136     my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
1137     $dec           = length $dec;
1138     my $decimalplaces = ($dec > 2) ? $dec : 2;
1139
1140     # copy delivery date from reqdate for order -> invoice conversion
1141     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
1142       unless $form->{"deliverydate_$i"};
1143
1144
1145     $form->{"sellprice_$i"} =
1146       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
1147                            $decimalplaces);
1148
1149     $form->{"lastcost_$i"} =
1150       $form->format_amount(\%myconfig, $form->{"lastcost_$i"},
1151                            $decimalplaces);
1152
1153     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
1154     $dec_qty = length $dec_qty;
1155     $form->{"qty_$i"} =
1156       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
1157
1158   }
1159
1160   display_form();
1161
1162   $main::lxdebug->leave_sub();
1163 }
1164
1165 sub invoice_multi {
1166   $main::lxdebug->enter_sub();
1167
1168   my $form     = $main::form;
1169   my %myconfig = %main::myconfig;
1170   my $locale   = $main::locale;
1171
1172   check_do_access();
1173   $main::auth->assert($form->{type} eq 'sales_delivery_order' ? 'invoice_edit' : 'vendor_invoice_edit');
1174
1175   my @do_ids = map { $form->{"trans_id_$_"} } grep { $form->{"multi_id_$_"} } (1..$form->{rowcount});
1176
1177   if (!scalar @do_ids) {
1178     $form->show_generic_error($locale->text('You have not selected any delivery order.'));
1179   }
1180
1181   map { delete $form->{$_} } grep { m/^(?:trans|multi)_id_\d+/ } keys %{ $form };
1182
1183   if (!DO->retrieve('vc' => $form->{vc}, 'ids' => \@do_ids)) {
1184     $form->show_generic_error($form->{vc} eq 'customer' ?
1185                               $locale->text('You cannot create an invoice for delivery orders for different customers.') :
1186                               $locale->text('You cannot create an invoice for delivery orders from different vendors.'),
1187                               'back_button' => 1);
1188   }
1189
1190   my $source_type              = $form->{type};
1191   $form->{convert_from_do_ids} = join ' ', @do_ids;
1192   # bei der auswahl von mehreren Lieferscheinen fuer eine Rechnung, die einfach in donumber_array
1193   # zwischenspeichern (DO.pm) und als ' '-separierte Liste wieder zurueckschreiben
1194   # Hinweis: delete gibt den wert zurueck und loescht danach das element (nett und einfach)
1195   # $shell: perldoc perlunc; /delete EXPR
1196   $form->{donumber}            = delete $form->{donumber_array};
1197   $form->{ordnumber}           = delete $form->{ordnumber_array};
1198   $form->{cusordnumber}        = delete $form->{cusordnumber_array};
1199   $form->{deliverydate}        = $form->{transdate};
1200   $form->{transdate}           = $form->current_date(\%myconfig);
1201   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1202   $form->{type}                = "invoice";
1203   $form->{closed}              = 0;
1204   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
1205
1206   my ($script, $buysell);
1207   if ($source_type eq 'purchase_delivery_order') {
1208     $form->{title}  = $locale->text('Add Vendor Invoice');
1209     $form->{script} = 'ir.pl';
1210     $script         = "ir";
1211     $buysell        = 'sell';
1212
1213   } else {
1214     $form->{title}  = $locale->text('Add Sales Invoice');
1215     $form->{script} = 'is.pl';
1216     $script         = "is";
1217     $buysell        = 'buy';
1218   }
1219
1220   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
1221
1222   # get vendor or customer discount
1223   my $vc_discount;
1224   my $saved_form = save_form();
1225   if ($form->{vc} eq 'vendor') {
1226     IR->get_vendor(\%myconfig, \%$form);
1227     $vc_discount = $form->{vendor_discount};
1228   } else {
1229     IS->get_customer(\%myconfig, \%$form);
1230     $vc_discount = $form->{customer_discount};
1231   }
1232   # use payment terms from customer or vendor
1233   restore_form($saved_form,0,qw(payment_id));
1234
1235   $form->{rowcount} = 0;
1236   foreach my $ref (@{ $form->{form_details} }) {
1237     $form->{rowcount}++;
1238     $ref->{reqdate} ||= $ref->{dord_transdate}; # copy transdates into each invoice row
1239     map { $form->{"${_}_$form->{rowcount}"} = $ref->{$_} } keys %{ $ref };
1240     map { $form->{"${_}_$form->{rowcount}"} = $form->format_amount(\%myconfig, $ref->{$_}) } qw(qty sellprice lastcost);
1241     $form->{"converted_from_delivery_order_items_id_$form->{rowcount}"} = delete $form->{"delivery_order_items_id_$form->{rowcount}"};
1242
1243     if ($vc_discount){ # falls wir einen Lieferanten/Kundenrabatt haben
1244       # und keinen anderen discount wert an $i ...
1245       $form->{"discount_$form->{rowcount}"} ||= $vc_discount; # ... nehmen wir diesen Rabatt
1246     }
1247
1248     $form->{"discount_$form->{rowcount}"}   = $form->{"discount_$form->{rowcount}"}  * 100; #s.a. Bug 1151
1249     # Anm.: Eine Änderung des discounts in der SL/DO.pm->retrieve (select (doi.discount * 100) as discount) ergibt in psql einen
1250     # Wert von 10.0000001490116. Ferner ist der Rabatt in der Rechnung dann bei 1.0 (?). Deswegen lasse ich das hier. jb 10.10.09
1251
1252     $form->{"discount_$form->{rowcount}"} = $form->format_amount(\%myconfig, $form->{"discount_$form->{rowcount}"});
1253   }
1254   delete $form->{form_details};
1255
1256   $locale = Locale->new("$myconfig{countrycode}", "$script");
1257
1258   require "bin/mozilla/$form->{script}";
1259
1260   invoice_links();
1261   prepare_invoice();
1262
1263   display_form();
1264
1265   $main::lxdebug->leave_sub();
1266 }
1267
1268 sub save_as_new {
1269   $main::lxdebug->enter_sub();
1270
1271   check_do_access();
1272
1273   my $form     = $main::form;
1274
1275   $form->{saveasnew} = 1;
1276   $form->{closed}    = 0;
1277   $form->{delivered} = 0;
1278   map { delete $form->{$_} } qw(printed emailed queued);
1279   delete @{ $form }{ grep { m/^stock_(?:in|out)_\d+/ } keys %{ $form } };
1280   $form->{"converted_from_delivery_order_items_id_$_"} = delete $form->{"delivery_order_items_id_$_"} for 1 .. $form->{"rowcount"};
1281   # Let kivitendo assign a new order number if the user hasn't changed the
1282   # previous one. If it has been changed manually then use it as-is.
1283   $form->{donumber} =~ s/^\s*//g;
1284   $form->{donumber} =~ s/\s*$//g;
1285   if ($form->{saved_donumber} && ($form->{saved_donumber} eq $form->{donumber})) {
1286     delete($form->{donumber});
1287   }
1288
1289   save();
1290
1291   $main::lxdebug->leave_sub();
1292 }
1293
1294 sub calculate_stock_in_out {
1295   $main::lxdebug->enter_sub();
1296
1297   my $form     = $main::form;
1298
1299   my $i = shift;
1300
1301   if (!$form->{"id_${i}"}) {
1302     $main::lxdebug->leave_sub();
1303     return '';
1304   }
1305
1306   my $all_units = AM->retrieve_all_units();
1307
1308   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
1309   my $sinfo    = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_${i}"});
1310
1311   my $do_qty   = AM->sum_with_unit($::form->{"qty_$i"}, $::form->{"unit_$i"});
1312   my $sum      = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $sinfo });
1313   my $matches  = $do_qty == $sum;
1314
1315   my $amount_unit = $all_units->{$form->{"partunit_$i"}}->{base_unit};
1316   my $content     = $form->format_amount(\%::myconfig, AM->convert_unit($amount_unit, $form->{"unit_$i"}) * $sum * 1) . ' ' . $form->{"unit_$i"};
1317
1318   $content     = qq|<span id="stock_in_out_qty_display_${i}">${content}</span><input type=hidden id='stock_in_out_qty_matches_$i' value='$matches'> <input type="button" onclick="open_stock_in_out_window('${in_out}', $i);" value="?">|;
1319
1320   $main::lxdebug->leave_sub();
1321
1322   return $content;
1323 }
1324
1325 sub get_basic_bin_wh_info {
1326   $main::lxdebug->enter_sub();
1327
1328   my $stock_info = shift;
1329
1330   my $form     = $main::form;
1331
1332   foreach my $sinfo (@{ $stock_info }) {
1333     next unless ($sinfo->{bin_id});
1334
1335     my $bin_info = WH->get_basic_bin_info('id' => $sinfo->{bin_id});
1336     map { $sinfo->{"${_}_description"} = $sinfo->{"${_}description"} = $bin_info->{"${_}_description"} } qw(bin warehouse);
1337   }
1338
1339   $main::lxdebug->leave_sub();
1340 }
1341
1342 sub stock_in_out_form {
1343   $main::lxdebug->enter_sub();
1344
1345   my $form     = $main::form;
1346
1347   if ($form->{in_out} eq 'out') {
1348     stock_out_form();
1349   } else {
1350     stock_in_form();
1351   }
1352
1353   $main::lxdebug->leave_sub();
1354 }
1355
1356 sub redo_stock_info {
1357   $main::lxdebug->enter_sub();
1358
1359   my %params    = @_;
1360
1361   my $form     = $main::form;
1362
1363   my @non_empty = grep { $_->{qty} } @{ $params{stock_info} };
1364
1365   if ($params{add_empty_row}) {
1366     push @non_empty, {
1367       'warehouse_id' => scalar(@non_empty) ? $non_empty[-1]->{warehouse_id} : undef,
1368       'bin_id'       => scalar(@non_empty) ? $non_empty[-1]->{bin_id}       : undef,
1369     };
1370   }
1371
1372   @{ $params{stock_info} } = @non_empty;
1373
1374   $main::lxdebug->leave_sub();
1375 }
1376
1377 sub update_stock_in {
1378   $main::lxdebug->enter_sub();
1379
1380   my $form     = $main::form;
1381   my %myconfig = %main::myconfig;
1382
1383   my $stock_info = [];
1384
1385   foreach my $i (1..$form->{rowcount}) {
1386     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1387     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber
1388                                                                    bestbefore qty unit delivery_order_items_stock_id) };
1389   }
1390
1391   display_stock_in_form($stock_info);
1392
1393   $main::lxdebug->leave_sub();
1394 }
1395
1396 sub stock_in_form {
1397   $main::lxdebug->enter_sub();
1398
1399   my $form     = $main::form;
1400
1401   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
1402
1403   display_stock_in_form($stock_info);
1404
1405   $main::lxdebug->leave_sub();
1406 }
1407
1408 sub display_stock_in_form {
1409   $main::lxdebug->enter_sub();
1410
1411   my $stock_info = shift;
1412
1413   my $form     = $main::form;
1414   my %myconfig = %main::myconfig;
1415   my $locale   = $main::locale;
1416
1417   $form->{title} = $locale->text('Stock');
1418
1419   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
1420
1421   # Standardlagerplatz für Standard-Auslagern verwenden, falls keiner für die Ware explizit definiert wurde
1422   if ($::instance_conf->get_transfer_default_use_master_default_bin) {
1423     $part_info->{warehouse_id} ||= $::instance_conf->get_warehouse_id;
1424     $part_info->{bin_id}       ||= $::instance_conf->get_bin_id;
1425   }
1426
1427   my $units      = AM->retrieve_units(\%myconfig, $form);
1428   # der zweite Parameter von unit_select_data gibt den default-Namen (selected) vor
1429   my $units_data = AM->unit_select_data($units, $form->{do_unit}, undef, $part_info->{unit});
1430
1431   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
1432                                      'bins'   => 'BINS' });
1433
1434   redo_stock_info('stock_info' => $stock_info, 'add_empty_row' => !$form->{delivered});
1435
1436   get_basic_bin_wh_info($stock_info);
1437
1438   $form->header(no_layout => 1);
1439   print $form->parse_html_template('do/stock_in_form', { 'UNITS'      => $units_data,
1440                                                          'STOCK_INFO' => $stock_info,
1441                                                          'PART_INFO'  => $part_info, });
1442
1443   $main::lxdebug->leave_sub();
1444 }
1445
1446 sub _stock_in_out_set_qty_display {
1447   my $stock_info       = shift;
1448   my $form             = $::form;
1449   my $all_units        = AM->retrieve_all_units();
1450   my $sum              = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $stock_info });
1451   my $amount_unit      = $all_units->{$form->{"partunit"}}->{base_unit};
1452   $form->{qty_display} = $form->format_amount(\%::myconfig, AM->convert_unit($amount_unit, $form->{"do_unit"}) * $sum * 1) . ' ' . $form->{"do_unit"};
1453 }
1454
1455 sub set_stock_in {
1456   $main::lxdebug->enter_sub();
1457
1458   my $form     = $main::form;
1459   my %myconfig = %main::myconfig;
1460
1461   my $stock_info = [];
1462
1463   foreach my $i (1..$form->{rowcount}) {
1464     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1465
1466     next if ($form->{"qty_$i"} <= 0);
1467
1468     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(delivery_order_items_stock_id warehouse_id bin_id chargenumber bestbefore qty unit) };
1469   }
1470
1471   $form->{stock} = SL::YAML::Dump($stock_info);
1472
1473   _stock_in_out_set_qty_display($stock_info);
1474
1475   my $do_qty       = AM->sum_with_unit($::form->parse_amount(\%::myconfig, $::form->{do_qty}), $::form->{do_unit});
1476   my $transfer_qty = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $stock_info });
1477
1478   $form->header();
1479   print $form->parse_html_template('do/set_stock_in_out', {
1480     qty_matches => $do_qty == $transfer_qty,
1481   });
1482
1483   $main::lxdebug->leave_sub();
1484 }
1485
1486 sub stock_out_form {
1487   $main::lxdebug->enter_sub();
1488
1489   my $form     = $main::form;
1490   my %myconfig = %main::myconfig;
1491   my $locale   = $main::locale;
1492
1493   $form->{title} = $locale->text('Release From Stock');
1494
1495   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
1496
1497   my $units      = AM->retrieve_units(\%myconfig, $form);
1498   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
1499
1500   my @contents   = DO->get_item_availability('parts_id' => $form->{parts_id});
1501
1502   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
1503
1504   if (!$form->{delivered}) {
1505     foreach my $row (@contents) {
1506       $row->{available_qty} = $form->format_amount(\%::myconfig, $row->{qty} * 1) . ' ' . $part_info->{unit};
1507
1508       foreach my $sinfo (@{ $stock_info }) {
1509         next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
1510                  ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1511                  ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
1512                  ($row->{bestbefore}   ne $sinfo->{bestbefore}));
1513
1514         map { $row->{"stock_$_"} = $sinfo->{$_} } qw(qty unit error delivery_order_items_stock_id);
1515       }
1516     }
1517
1518   } else {
1519     get_basic_bin_wh_info($stock_info);
1520
1521     foreach my $sinfo (@{ $stock_info }) {
1522       map { $sinfo->{"stock_$_"} = $sinfo->{$_} } qw(qty unit);
1523     }
1524   }
1525
1526   $form->header(no_layout => 1);
1527   print $form->parse_html_template('do/stock_out_form', { 'UNITS'      => $units_data,
1528                                                           'WHCONTENTS' => $form->{delivered} ? $stock_info : \@contents,
1529                                                           'PART_INFO'  => $part_info, });
1530
1531   $main::lxdebug->leave_sub();
1532 }
1533
1534 sub set_stock_out {
1535   $main::lxdebug->enter_sub();
1536
1537   my $form     = $main::form;
1538   my %myconfig = %main::myconfig;
1539   my $locale   = $main::locale;
1540
1541   my $stock_info = [];
1542
1543   foreach my $i (1 .. $form->{rowcount}) {
1544     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1545
1546     next if ($form->{"qty_$i"} <= 0);
1547
1548     push @{ $stock_info }, {
1549       'warehouse_id' => $form->{"warehouse_id_$i"},
1550       'bin_id'       => $form->{"bin_id_$i"},
1551       'chargenumber' => $form->{"chargenumber_$i"},
1552       'bestbefore'   => $form->{"bestbefore_$i"},
1553       'qty'          => $form->{"qty_$i"},
1554       'unit'         => $form->{"unit_$i"},
1555       'row'          => $i,
1556       'delivery_order_items_stock_id'  => $form->{"delivery_order_items_stock_id_$i"},
1557     };
1558   }
1559
1560   my @errors     = DO->check_stock_availability('requests' => $stock_info,
1561                                                 'parts_id' => $form->{parts_id});
1562
1563   $form->{stock} = SL::YAML::Dump($stock_info);
1564
1565   if (@errors) {
1566     $form->{ERRORS} = [];
1567     map { push @{ $form->{ERRORS} }, $locale->text('Error in row #1: The quantity you entered is bigger than the stocked quantity.', $_->{row}); } @errors;
1568     stock_in_out_form();
1569
1570   } else {
1571     _stock_in_out_set_qty_display($stock_info);
1572
1573     my $do_qty       = AM->sum_with_unit($::form->parse_amount(\%::myconfig, $::form->{do_qty}), $::form->{do_unit});
1574     my $transfer_qty = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $stock_info });
1575
1576     $form->header();
1577     print $form->parse_html_template('do/set_stock_in_out', {
1578       qty_matches => $do_qty == $transfer_qty,
1579     });
1580   }
1581
1582   $main::lxdebug->leave_sub();
1583 }
1584
1585 sub transfer_in {
1586   $main::lxdebug->enter_sub();
1587
1588   my $form     = $main::form;
1589   my %myconfig = %main::myconfig;
1590   my $locale   = $main::locale;
1591
1592   if ($form->{id} && DO->is_marked_as_delivered(id => $form->{id})) {
1593     $form->show_generic_error($locale->text('The parts for this delivery order have already been transferred in.'));
1594   }
1595
1596   save(no_redirect => 1);
1597
1598   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_in_${_}"} } (1 .. $form->{rowcount});
1599   my @all_requests;
1600
1601   if (@part_ids) {
1602     my $units         = AM->retrieve_units(\%myconfig, $form);
1603     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1604     my %request_map;
1605
1606     $form->{ERRORS}   = [];
1607
1608     foreach my $i (1 .. $form->{rowcount}) {
1609       next unless ($form->{"id_$i"} && $form->{"stock_in_$i"});
1610
1611       my $row_sum_base_qty = 0;
1612       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1613
1614       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_in_$i"}) }) {
1615         $request->{parts_id}  = $form->{"id_$i"};
1616         $row_sum_base_qty    += $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1617
1618         $request->{project_id} = $form->{"project_id_$i"} || $form->{globalproject_id};
1619
1620         push @all_requests, $request;
1621       }
1622
1623       next if (0 == $row_sum_base_qty);
1624
1625       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1626
1627 #      if ($do_base_qty != $row_sum_base_qty) {
1628 #        push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no stock at all or the full quantity of #2 #3.',
1629 #                                                 $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1630 #      }
1631     }
1632
1633     if (@{ $form->{ERRORS} }) {
1634       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been marked as delivered. The warehouse contents have not changed.');
1635
1636       set_headings('edit');
1637       update();
1638       $main::lxdebug->leave_sub();
1639
1640       $::dispatcher->end_request;
1641     }
1642   }
1643
1644   DO->transfer_in_out('direction' => 'in',
1645                       'requests'  => \@all_requests);
1646
1647   SL::DB::DeliveryOrder->new(id => $form->{id})->load->update_attributes(delivered => 1);
1648
1649   flash_later('info', $locale->text("Transfer successful"));
1650   $form->{callback} = 'do.pl?action=edit&type=purchase_delivery_order&id=' . $form->escape($form->{id});
1651   $form->redirect;
1652
1653   $main::lxdebug->leave_sub();
1654 }
1655
1656 sub transfer_out {
1657   $main::lxdebug->enter_sub();
1658
1659   my $form     = $main::form;
1660   my %myconfig = %main::myconfig;
1661   my $locale   = $main::locale;
1662
1663   if ($form->{id} && DO->is_marked_as_delivered(id => $form->{id})) {
1664     $form->show_generic_error($locale->text('The parts for this delivery order have already been transferred out.'));
1665   }
1666
1667   save(no_redirect => 1);
1668
1669   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_out_${_}"} } (1 .. $form->{rowcount});
1670   my @all_requests;
1671
1672   if (@part_ids) {
1673     my $units         = AM->retrieve_units(\%myconfig, $form);
1674     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1675     my %request_map;
1676
1677     $form->{ERRORS}   = [];
1678
1679     foreach my $i (1 .. $form->{rowcount}) {
1680       next unless ($form->{"id_$i"} && $form->{"stock_out_$i"});
1681
1682       my $row_sum_base_qty = 0;
1683       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1684
1685       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_out_$i"}) }) {
1686         $request->{parts_id} = $form->{"id_$i"};
1687         $request->{base_qty} = $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1688         $request->{project_id} = $form->{"project_id_$i"} ? $form->{"project_id_$i"} : $form->{globalproject_id};
1689
1690         my $map_key          = join '--', ($form->{"id_$i"}, @{$request}{qw(warehouse_id bin_id chargenumber bestbefore)});
1691
1692         $request_map{$map_key}                 ||= $request;
1693         $request_map{$map_key}->{sum_base_qty} ||= 0;
1694         $request_map{$map_key}->{sum_base_qty}  += $request->{base_qty};
1695         $row_sum_base_qty                       += $request->{base_qty};
1696
1697         push @all_requests, $request;
1698       }
1699
1700       next if (0 == $row_sum_base_qty);
1701
1702       my $do_base_qty = $form->{"qty_$i"} * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1703
1704 #      if ($do_base_qty != $row_sum_base_qty) {
1705 #        push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no transfer at all or the full quantity of #2 #3.',
1706 #                                                 $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1707 #      }
1708     }
1709
1710     if (%request_map) {
1711       my @bin_ids      = map { $_->{bin_id} } values %request_map;
1712       my %bin_info_map = WH->get_basic_bin_info('id' => \@bin_ids);
1713       my @contents     = DO->get_item_availability('parts_id' => \@part_ids);
1714
1715       foreach my $inv (@contents) {
1716         my $map_key = join '--', @{$inv}{qw(parts_id warehouse_id bin_id chargenumber bestbefore)};
1717
1718         next unless ($request_map{$map_key});
1719
1720         my $request    = $request_map{$map_key};
1721         $request->{ok} = $request->{sum_base_qty} <= $inv->{qty};
1722       }
1723
1724       foreach my $request (values %request_map) {
1725         next if ($request->{ok});
1726
1727         my $pinfo = $part_info_map{$request->{parts_id}};
1728         my $binfo = $bin_info_map{$request->{bin_id}};
1729
1730         if ($::instance_conf->get_show_bestbefore) {
1731             push @{ $form->{ERRORS} }, $locale->text("There is not enough available of '#1' at warehouse '#2', bin '#3', #4, #5, for the transfer of #6.",
1732                                                      $pinfo->{description},
1733                                                      $binfo->{warehouse_description},
1734                                                      $binfo->{bin_description},
1735                                                      $request->{chargenumber} ? $locale->text('chargenumber #1', $request->{chargenumber}) : $locale->text('no chargenumber'),
1736                                                      $request->{bestbefore} ? $locale->text('bestbefore #1', $request->{bestbefore}) : $locale->text('no bestbefore'),
1737                                                      $form->format_amount(\%::myconfig, $request->{sum_base_qty}) . ' ' . $pinfo->{unit});
1738         } else {
1739             push @{ $form->{ERRORS} }, $locale->text("There is not enough available of '#1' at warehouse '#2', bin '#3', #4, for the transfer of #5.",
1740                                                      $pinfo->{description},
1741                                                      $binfo->{warehouse_description},
1742                                                      $binfo->{bin_description},
1743                                                      $request->{chargenumber} ? $locale->text('chargenumber #1', $request->{chargenumber}) : $locale->text('no chargenumber'),
1744                                                      $form->format_amount(\%::myconfig, $request->{sum_base_qty}) . ' ' . $pinfo->{unit});
1745         }
1746       }
1747     }
1748
1749     if (@{ $form->{ERRORS} }) {
1750       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been marked as delivered. The warehouse contents have not changed.');
1751
1752       set_headings('edit');
1753       update();
1754       $main::lxdebug->leave_sub();
1755
1756       $::dispatcher->end_request;
1757     }
1758   }
1759   DO->transfer_in_out('direction' => 'out',
1760                       'requests'  => \@all_requests);
1761
1762   SL::DB::DeliveryOrder->new(id => $form->{id})->load->update_attributes(delivered => 1);
1763
1764   flash_later('info', $locale->text("Transfer successful"));
1765   $form->{callback} = 'do.pl?action=edit&type=sales_delivery_order&id=' . $form->escape($form->{id});
1766   $form->redirect;
1767
1768   $main::lxdebug->leave_sub();
1769 }
1770
1771 sub mark_closed {
1772   $main::lxdebug->enter_sub();
1773
1774   my $form     = $main::form;
1775
1776   DO->close_orders('ids' => [ $form->{id} ]);
1777
1778   $form->{closed} = 1;
1779
1780   update();
1781
1782   $main::lxdebug->leave_sub();
1783 }
1784
1785 sub display_form {
1786   $::lxdebug->enter_sub;
1787
1788   $::auth->assert('purchase_delivery_order_edit | sales_delivery_order_edit');
1789
1790   relink_accounts();
1791   retrieve_partunits();
1792
1793   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1794   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1795
1796   $::form->language_payment(\%::myconfig);
1797
1798   Common::webdav_folder($::form);
1799
1800   form_header();
1801   display_row(++$::form->{rowcount});
1802   form_footer();
1803
1804   $::lxdebug->leave_sub;
1805 }
1806
1807 sub yes {
1808   call_sub($main::form->{yes_nextsub});
1809 }
1810
1811 sub no {
1812   call_sub($main::form->{no_nextsub});
1813 }
1814
1815 sub update {
1816   call_sub($main::form->{update_nextsub} || $main::form->{nextsub} || 'update_delivery_order');
1817 }
1818
1819 sub dispatcher {
1820   my $form     = $main::form;
1821   my $locale   = $main::locale;
1822
1823   foreach my $action (qw(update print save transfer_out transfer_out_default sort
1824                          transfer_in transfer_in_default mark_closed save_as_new invoice delete)) {
1825     if ($form->{"action_${action}"}) {
1826       call_sub($action);
1827       return;
1828     }
1829   }
1830
1831   $form->error($locale->text('No action defined.'));
1832 }
1833
1834 sub transfer_out_default {
1835   $main::lxdebug->enter_sub();
1836
1837   my $form     = $main::form;
1838
1839   transfer_in_out_default('direction' => 'out');
1840
1841   $main::lxdebug->leave_sub();
1842 }
1843
1844 sub transfer_in_default {
1845   $main::lxdebug->enter_sub();
1846
1847   my $form     = $main::form;
1848
1849   transfer_in_out_default('direction' => 'in');
1850
1851   $main::lxdebug->leave_sub();
1852 }
1853
1854 # Falls das Standardlagerverfahren aktiv ist, wird
1855 # geprüft, ob alle Standardlagerplätze für die Auslager-
1856 # artikel vorhanden sind UND ob die Warenmenge ausreicht zum
1857 # Auslagern. Falls nicht wird entsprechend eine Fehlermeldung
1858 # generiert. Offen Chargennummer / bestbefore wird nicht berücksichtigt
1859 sub transfer_in_out_default {
1860   $main::lxdebug->enter_sub();
1861
1862   my $form     = $main::form;
1863   my %myconfig = %main::myconfig;
1864   my $locale   = $main::locale;
1865   my %params   = @_;
1866
1867   my (%missing_default_bins, %qty_parts, @all_requests, %part_info_map, $default_warehouse_id, $default_bin_id);
1868
1869   Common::check_params(\%params, qw(direction));
1870
1871   # entsprechende defaults holen, falls standardlagerplatz verwendet werden soll
1872   if ($::instance_conf->get_transfer_default_use_master_default_bin) {
1873     $default_warehouse_id = $::instance_conf->get_warehouse_id;
1874     $default_bin_id       = $::instance_conf->get_bin_id;
1875   }
1876
1877
1878   my @part_ids = map { $form->{"id_${_}"} } (1 .. $form->{rowcount});
1879   if (@part_ids) {
1880     my $units         = AM->retrieve_units(\%myconfig, $form);
1881     %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1882     foreach my $i (1 .. $form->{rowcount}) {
1883       next unless ($form->{"id_$i"});
1884       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1885       my $qty =   $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1886
1887       $form->show_generic_error($locale->text("Cannot transfer negative entries." )) if ($qty < 0);
1888       # if we do not want to transfer services and this part is a service, set qty to zero
1889       # ... and do not create a hash entry in %qty_parts below (will skip check for bins for the transfer == out case)
1890       # ... and push only a empty (undef) element to @all_requests (will skip check for bin_id and warehouse_id and will not alter the row)
1891
1892       $qty = 0 if (!$::instance_conf->get_transfer_default_services && $part_info_map{$form->{"id_$i"}}->{part_type} eq 'service');
1893       $qty_parts{$form->{"id_$i"}} += $qty;
1894       if ($qty == 0) {
1895         delete $qty_parts{$form->{"id_$i"}} unless $qty_parts{$form->{"id_$i"}};
1896         undef $form->{"stock_in_$i"};
1897       }
1898
1899       $part_info_map{$form->{"id_$i"}}{bin_id}       ||= $default_bin_id;
1900       $part_info_map{$form->{"id_$i"}}{warehouse_id} ||= $default_warehouse_id;
1901
1902       push @all_requests, ($qty == 0) ? { } : {
1903                         'chargenumber' => '',  #?? die müsste entsprechend geholt werden
1904                         #'bestbefore' => undef, # TODO wird nicht berücksichtigt
1905                         'bin_id' => $part_info_map{$form->{"id_$i"}}{bin_id},
1906                         'qty' => $qty,
1907                         'parts_id' => $form->{"id_$i"},
1908                         'comment' => $locale->text("Default transfer delivery order"),
1909                         'unit' => $part_info_map{$form->{"id_$i"}}{unit},
1910                         'warehouse_id' => $part_info_map{$form->{"id_$i"}}{warehouse_id},
1911                         'oe_id' => $form->{id},
1912                         'project_id' => $form->{"project_id_$i"} ? $form->{"project_id_$i"} : $form->{globalproject_id}
1913                       };
1914     }
1915
1916     # jetzt wird erst überprüft, ob die Stückzahl entsprechend stimmt.
1917     # check if bin (transfer in and transfer out and qty (transfer out) is correct
1918     foreach my $key (keys %qty_parts) {
1919
1920       $missing_default_bins{$key}{missing_bin} = 1 unless ($part_info_map{$key}{bin_id});
1921       next unless ($part_info_map{$key}{bin_id}); # abbruch
1922
1923       if ($params{direction} eq 'out') {  # wird nur für ausgehende Mengen benötigt
1924         my ($max_qty, $error) = WH->get_max_qty_parts_bin(parts_id => $key, bin_id => $part_info_map{$key}{bin_id});
1925         if ($error == 1) {
1926           # wir können nicht entscheiden, welche charge oder mhd (bestbefore) ausgewählt sein soll
1927           # deshalb rückmeldung nach oben geben, manuell auszulagern
1928           # TODO Bei nur einem Treffer mit Charge oder bestbefore wäre das noch möglich
1929           $missing_default_bins{$key}{chargenumber} = 1;
1930         }
1931         if ($max_qty < $qty_parts{$key}){
1932           $missing_default_bins{$key}{missing_qty} = $max_qty - $qty_parts{$key};
1933         }
1934       }
1935     }
1936   } # if @parts_id
1937
1938   # Abfrage für Fehlerbehandlung (nur bei direction == out)
1939   if (scalar (keys %missing_default_bins)) {
1940     my $fehlertext;
1941     foreach my $fehler (keys %missing_default_bins) {
1942
1943       my $ware = WH->get_part_description(parts_id => $fehler);
1944       if ($missing_default_bins{$fehler}{missing_bin}){
1945         $fehlertext .= "Kein Standardlagerplatz definiert bei $ware <br>";
1946       }
1947       if ($missing_default_bins{$fehler}{missing_qty}) {  # missing_qty
1948         $fehlertext .= "Es fehlen " . $missing_default_bins{$fehler}{missing_qty}*-1 .
1949                        " von $ware auf dem Standard-Lagerplatz " . $part_info_map{$fehler}{bin} .   " zum Auslagern<br>";
1950       }
1951       if ($missing_default_bins{$fehler}{chargenumber}){
1952         $fehlertext .= "Die Ware hat eine Chargennummer oder eine Mindesthaltbarkeit definiert.
1953                         Hier kann man nicht automatisch entscheiden.
1954                         Bitte diesen Lieferschein manuell auslagern.
1955                         Bei: $ware";
1956       }
1957       # auslagern soll immer gehen, auch wenn nicht genügend auf lager ist.
1958       # der lagerplatz ist hier extra konfigurierbar, bspw. Lager-Korrektur mit
1959       # Lagerplatz Lagerplatz-Korrektur
1960       my $default_warehouse_id_ignore_onhand = $::instance_conf->get_warehouse_id_ignore_onhand;
1961       my $default_bin_id_ignore_onhand       = $::instance_conf->get_bin_id_ignore_onhand;
1962       if ($::instance_conf->get_transfer_default_ignore_onhand && $default_bin_id_ignore_onhand) {
1963         # entsprechende defaults holen
1964         # falls chargenumber, bestbefore oder anzahl nicht stimmt, auf automatischen
1965         # lagerplatz wegbuchen!
1966         foreach (@all_requests) {
1967           if ($_->{parts_id} eq $fehler){
1968           $_->{bin_id}        = $default_bin_id_ignore_onhand;
1969           $_->{warehouse_id}  = $default_warehouse_id_ignore_onhand;
1970           }
1971         }
1972       } else {
1973         #$main::lxdebug->message(0, 'Fehlertext: ' . $fehlertext);
1974         $form->show_generic_error($locale->text("Cannot transfer. <br> Reason:<br>#1", $fehlertext ));
1975       }
1976     }
1977   }
1978
1979
1980   # hier der eigentliche fallunterschied für in oder out
1981   my $prefix   = $params{direction} eq 'in' ? 'in' : 'out';
1982
1983   # dieser array_ref ist für DO->save da:
1984   # einmal die all_requests in YAML verwandeln, damit delivery_order_items_stock
1985   # gefüllt werden kann.
1986   # could be dumped to the form in the first loop,
1987   # but maybe bin_id and warehouse_id has changed to the "korrekturlager" with
1988   # allowed negative qty ($::instance_conf->get_warehouse_id_ignore_onhand) ...
1989   my $i = 0;
1990   foreach (@all_requests){
1991     $i++;
1992     next unless scalar(%{ $_ });
1993     $form->{"stock_${prefix}_$i"} = SL::YAML::Dump([$_]);
1994   }
1995
1996   save(no_redirect => 1); # Wir können auslagern, deshalb beleg speichern
1997                           # und in delivery_order_items_stock speichern
1998
1999   # ... and fill back the persistent dois_id for inventory fk
2000   undef (@all_requests);
2001   foreach my $i (1 .. $form->{rowcount}) {
2002     next unless ($form->{"id_$i"} && $form->{"stock_${prefix}_$i"});
2003     push @all_requests, @{ DO->unpack_stock_information('packed' => $form->{"stock_${prefix}_$i"}) };
2004   }
2005   DO->transfer_in_out('direction' => $prefix,
2006                       'requests'  => \@all_requests);
2007
2008   SL::DB::DeliveryOrder->new(id => $form->{id})->load->update_attributes(delivered => 1);
2009
2010   $form->{callback} = 'do.pl?action=edit&type=sales_delivery_order&id=' . $form->escape($form->{id}) if $params{direction} eq 'out';
2011   $form->{callback} = 'do.pl?action=edit&type=purchase_delivery_order&id=' . $form->escape($form->{id}) if $params{direction} eq 'in';
2012   $form->redirect;
2013
2014 }
2015
2016 sub sort {
2017   $main::lxdebug->enter_sub();
2018
2019   check_do_access();
2020
2021   my $form     = $main::form;
2022   my %temp_hash;
2023
2024   save(no_redirect => 1); # has to be done, at least for newly added positions
2025
2026   # hashify partnumbers, positions. key is delivery_order_items_id
2027   for my $i (1 .. ($form->{rowcount}) ) {
2028     $temp_hash{$form->{"delivery_order_items_id_$i"}} = { runningnumber => $form->{"runningnumber_$i"}, partnumber => $form->{"partnumber_$i"} };
2029     if ($form->{id} && $form->{"discount_$i"}) {
2030       # prepare_order assumes a db value if there is a form->id and multiplies *100
2031       # We hope for new controller code (no more format_amount/parse_amount distinction)
2032       $form->{"discount_$i"} /=100;
2033     }
2034   }
2035   # naturally sort partnumbers and get a sorted array of doi_ids
2036   my @sorted_doi_ids =  sort { Sort::Naturally::ncmp($temp_hash{$a}->{"partnumber"}, $temp_hash{$b}->{"partnumber"}) }  keys %temp_hash;
2037
2038
2039   my $new_number = 1;
2040
2041   for (@sorted_doi_ids) {
2042     $form->{"runningnumber_$temp_hash{$_}->{runningnumber}"} = $new_number;
2043     $new_number++;
2044   }
2045   # all parse_amounts changes are in form (i.e. , to .) therefore we need
2046   # another format_amount to change it back, for the next save ;-(
2047   # works great except for row discounts (see above comment)
2048   prepare_order();
2049
2050
2051     $main::lxdebug->leave_sub();
2052     save();
2053 }
2054
2055 __END__
2056
2057 =pod
2058
2059 =encoding utf8
2060
2061 =head1 NAME
2062
2063 do.pl - Script for all calls to delivery order
2064
2065 =head1 FUNCTIONS
2066
2067 =over 2
2068
2069 =item C<sort>
2070
2071 Sorts all position with Natural Sort. Can be activated in form_footer.html like this
2072 C<E<lt>input class="submit" type="submit" name="action_sort" id="sort_button" value="[% 'Sort and Save' | $T8 %]"E<gt>>
2073
2074 =back
2075
2076 =head1 TODO
2077
2078 Sort and Save can be implemented as an optional button if configuration ca be set by client config.
2079 Example coding for database scripts and templates in (git show af2f24b8), check also
2080 autogeneration for rose (scripts/rose_auto_create_model.pl --h)