Verkaufs- und Einkaufslieferschein um Standardlagerverfahren erweitert (#2284)
[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., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Delivery orders
31 #======================================================================
32
33 use List::Util qw(max sum);
34 use POSIX qw(strftime);
35 use YAML;
36
37 use SL::DB::DeliveryOrder;
38 use SL::DO;
39 use SL::IR;
40 use SL::IS;
41 use SL::ReportGenerator;
42 use SL::WH;
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/common.pl";
45 require "bin/mozilla/invoice_io.pl";
46 require "bin/mozilla/io.pl";
47 require "bin/mozilla/reportgenerator.pl";
48
49 use strict;
50
51 1;
52
53 # end of main
54
55 sub check_do_access {
56   $main::auth->assert($main::form->{type} . '_edit');
57 }
58
59 sub set_headings {
60   $main::lxdebug->enter_sub();
61
62   check_do_access();
63
64   my ($action) = @_;
65
66   my $form     = $main::form;
67   my $locale   = $main::locale;
68
69   if ($form->{type} eq 'purchase_delivery_order') {
70     $form->{vc}    = 'vendor';
71     $form->{title} = $action eq "edit" ? $locale->text('Edit Purchase Delivery Order') : $locale->text('Add Purchase Delivery Order');
72   } else {
73     $form->{vc}    = 'customer';
74     $form->{title} = $action eq "edit" ? $locale->text('Edit Sales Delivery Order') : $locale->text('Add Sales Delivery Order');
75   }
76
77   $form->{heading} = $locale->text('Delivery Order');
78
79   $main::lxdebug->leave_sub();
80 }
81
82 sub add {
83   $main::lxdebug->enter_sub();
84
85   check_do_access();
86
87   my $form     = $main::form;
88
89   set_headings("add");
90
91   $form->{callback} = build_std_url('action=add', 'type', 'vc') unless ($form->{callback});
92
93   order_links();
94   prepare_order();
95   display_form();
96
97   $main::lxdebug->leave_sub();
98 }
99
100 sub edit {
101   $main::lxdebug->enter_sub();
102
103   check_do_access();
104
105   my $form     = $main::form;
106
107   # show history button
108   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
109   #/show hhistory button
110
111   $form->{simple_save} = 0;
112
113   set_headings("edit");
114
115   # editing without stuff to edit? try adding it first
116   if ($form->{rowcount} && !$form->{print_and_save}) {
117 #     map { $id++ if $form->{"multi_id_$_"} } (1 .. $form->{rowcount});
118 #     if (!$id) {
119
120       # reset rowcount
121       undef $form->{rowcount};
122       add();
123       $main::lxdebug->leave_sub();
124       return;
125 #     }
126   } elsif (!$form->{id}) {
127     add();
128     $main::lxdebug->leave_sub();
129     return;
130   }
131
132   my ($language_id, $printer_id);
133   if ($form->{print_and_save}) {
134     $form->{action}   = "dispatcher";
135     $form->{action_print} = "1";
136     $form->{resubmit} = 1;
137     $language_id      = $form->{language_id};
138     $printer_id       = $form->{printer_id};
139   }
140
141   set_headings("edit");
142
143   order_links();
144   prepare_order();
145
146   if ($form->{print_and_save}) {
147     $form->{language_id} = $language_id;
148     $form->{printer_id}  = $printer_id;
149   }
150
151   display_form();
152
153   $main::lxdebug->leave_sub();
154 }
155
156 sub order_links {
157   $main::lxdebug->enter_sub();
158
159   check_do_access();
160
161   my $form     = $main::form;
162   my %myconfig = %main::myconfig;
163
164   # get customer/vendor
165   $form->all_vc(\%myconfig, $form->{vc}, ($form->{vc} eq 'customer') ? "AR" : "AP");
166
167   # retrieve order/quotation
168   $form->{webdav}   = $::lx_office_conf{features}->{webdav};
169   $form->{jsscript} = 1;
170
171   my $editing = $form->{id};
172
173   DO->retrieve('vc'  => $form->{vc},
174                'ids' => $form->{id});
175
176   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes currency));
177   $form->{shipto} = 1 if $form->{id} || $form->{convert_from_oe_ids};
178
179   # get customer / vendor
180   if ($form->{vc} eq 'vendor') {
181     IR->get_vendor(\%myconfig, \%$form);
182     $form->{discount} = $form->{vendor_discount};
183   } else {
184     IS->get_customer(\%myconfig, \%$form);
185     $form->{discount} = $form->{customer_discount};
186   }
187
188   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id));
189   $form->restore_vars(qw(currency)) if ($form->{id} || $form->{convert_from_oe_ids});
190   $form->restore_vars(qw(taxincluded)) if $form->{id};
191   $form->restore_vars(qw(salesman_id)) if $editing;
192
193   if ($form->{"all_$form->{vc}"}) {
194     unless ($form->{"$form->{vc}_id"}) {
195       $form->{"$form->{vc}_id"} = $form->{"all_$form->{vc}"}->[0]->{id};
196     }
197   }
198
199   ($form->{ $form->{vc} })  = split /--/, $form->{ $form->{vc} };
200   $form->{"old$form->{vc}"} = qq|$form->{$form->{vc}}--$form->{"$form->{vc}_id"}|;
201
202   $form->{employee} = "$form->{employee}--$form->{employee_id}";
203
204   $main::lxdebug->leave_sub();
205 }
206
207 sub prepare_order {
208   $main::lxdebug->enter_sub();
209
210   check_do_access();
211
212   my $form     = $main::form;
213   my %myconfig = %main::myconfig;
214
215   $form->{formname} = $form->{type} unless $form->{formname};
216
217   my $i = 0;
218   foreach my $ref (@{ $form->{form_details} }) {
219     $form->{rowcount} = ++$i;
220
221     map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
222   }
223   for my $i (1 .. $form->{rowcount}) {
224     if ($form->{id}) {
225       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
226     } else {
227       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"});
228     }
229     my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
230     $dec           = length $dec;
231     my $decimalplaces = ($dec > 2) ? $dec : 2;
232
233     # copy reqdate from deliverydate for invoice -> order conversion
234     $form->{"reqdate_$i"} = $form->{"deliverydate_$i"} unless $form->{"reqdate_$i"};
235
236     $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
237     $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
238
239     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
240     $dec_qty = length $dec_qty;
241     $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
242   }
243
244   $main::lxdebug->leave_sub();
245 }
246
247 sub form_header {
248   $main::lxdebug->enter_sub();
249
250   check_do_access();
251
252   my $form     = $main::form;
253   my %myconfig = %main::myconfig;
254
255   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
256   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
257
258   # use JavaScript Calendar or not
259   $form->{jsscript} = 1;
260
261   my @old_project_ids = ($form->{"globalproject_id"});
262   map({ push(@old_project_ids, $form->{"project_id_$_"})
263           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
264
265   my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
266   $form->get_lists("projects"       => {
267                      "key"          => "ALL_PROJECTS",
268                      "all"          => 0,
269                      "old_id"       => \@old_project_ids
270                    },
271                    $vc              => "ALL_VC",
272                    "price_factors"  => "ALL_PRICE_FACTORS",
273                    "departments"    => "ALL_DEPARTMENTS",
274                    "business_types" => "ALL_BUSINESS_TYPES",
275     );
276
277   $::form->{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
278   $::form->{ALL_SALESMEN}          = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
279   $::form->{ALL_SHIPTO}            = SL::DB::Manager::Shipto->get_all(query => [
280     or => [ trans_id  => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
281   ]);
282   $::form->{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all(query => [
283     or => [
284       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
285       and      => [
286         cp_cv_id => undef,
287         cp_id    => $::form->{cp_id} * 1
288       ]
289     ]
290   ]);
291
292   map { $_->{value} = "$_->{description}--$_->{id}" } @{ $form->{ALL_DEPARTMENTS} };
293   map { $_->{value} = "$_->{name}--$_->{id}"        } @{ $form->{ALL_VC} };
294
295   $form->{SHOW_VC_DROP_DOWN} =  $myconfig{vclimit} > scalar @{ $form->{ALL_VC} };
296
297   $form->{oldvcname}         =  $form->{"old$form->{vc}"};
298   $form->{oldvcname}         =~ s/--.*//;
299
300   if ($form->{resubmit}) {
301     my $dispatch_to_popup = '';
302     if ($form->{format} eq "html") {
303       $dispatch_to_popup .= "window.open('about:blank','Beleg'); document.do.target = 'Beleg';";
304     }
305     # emulate click for resubmitting actions
306     $dispatch_to_popup .= "document.do.${_}.click(); " for grep { /^action_/ } keys %$form;
307     $dispatch_to_popup .= "document.do.submit();";
308     $::request->{layout}->add_javascripts_inline("\$(function(){$dispatch_to_popup})");
309   }
310
311   my $follow_up_vc                =  $form->{ $form->{vc} eq 'customer' ? 'customer' : 'vendor' };
312   $follow_up_vc                   =~ s/--\d*\s*$//;
313
314   $form->{follow_up_trans_info} = $form->{donumber} .'('. $follow_up_vc .')';
315
316   $form->header();
317   # Fix für Bug 1082 Erwartet wird: 'abteilungsNAME--abteilungsID'
318   # und Erweiterung für Bug 1760:
319   # Das war leider nur ein Teil-Fix, da das Verhalten den 'Erneuern'-Knopf
320   # nicht überlebt. Konsequent jetzt auf L umgestellt
321   #   $ perldoc SL::Template::Plugin::L
322   # Daher entsprechend nur die Anpassung in form_header
323   # und in DO.pm gemacht. 4 Testfälle:
324   # department_id speichern                 | i.O.
325   # department_id lesen                     | i.O.
326   # department leer überlebt erneuern       | i.O.
327   # department nicht leer überlebt erneuern | i.O.
328   # $main::lxdebug->message(0, 'ABTEILUNGS ID in form?' . $form->{department_id});
329   print $form->parse_html_template('do/form_header');
330
331   $main::lxdebug->leave_sub();
332 }
333
334 sub form_footer {
335   $main::lxdebug->enter_sub();
336
337   check_do_access();
338
339   my $form     = $main::form;
340
341   $form->{PRINT_OPTIONS} = print_options('inline' => 1);
342
343   print $form->parse_html_template('do/form_footer',
344     {transfer_default         => ($::instance_conf->get_transfer_default)});
345
346   $main::lxdebug->leave_sub();
347 }
348
349 sub update_delivery_order {
350   $main::lxdebug->enter_sub();
351
352   check_do_access();
353
354   my $form     = $main::form;
355   my %myconfig = %main::myconfig;
356
357   set_headings($form->{"id"} ? "edit" : "add");
358
359   $form->{update} = 1;
360
361   my $payment_id;
362   $payment_id = $form->{payment_id} if $form->{payment_id};
363
364   check_name($form->{vc});
365   $form->{discount} =  $form->{"$form->{vc}_discount"} if defined $form->{"$form->{vc}_discount"};
366   # Problem: Wenn man ohne Erneuern einen Kunden/Lieferanten
367   # wechselt, wird der entsprechende Kunden/ Lieferantenrabatt
368   # nicht übernommen. Grundproblem: In Commit 82574e78
369   # hab ich aus discount customer_discount und vendor_discount
370   # gemacht und entsprechend an den Oberflächen richtig hin-
371   # geschoben. Die damals bessere Lösung wäre gewesen:
372   # In den Templates nur die hidden für form-discount wieder ein-
373   # setzen dann wäre die Verrenkung jetzt nicht notwendig.
374   # TODO: Ggf. Bugfix 1284, 1575 und 817 wieder zusammenführen
375   # Testfälle: Kunden mit Rabatt 0 -> Rabatt 20 i.O.
376   #            Kunde mit Rabatt 20 -> Rabatt 0  i.O.
377   #            Kunde mit Rabatt 20 -> Rabatt 5,5 i.O.
378   $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
379
380   # for pricegroups
381   my $i = $form->{rowcount};
382
383   if (   ($form->{"partnumber_$i"} eq "")
384       && ($form->{"description_$i"} eq "")
385       && ($form->{"partsgroup_$i"}  eq "")) {
386
387     check_form();
388
389   } else {
390
391     my $mode;
392     if ($form->{type} eq 'purchase_delivery_order') {
393       IR->retrieve_item(\%myconfig, $form);
394       $mode = 'IR';
395     } else {
396       IS->retrieve_item(\%myconfig, $form);
397       $mode = 'IS';
398     }
399
400     my $rows = scalar @{ $form->{item_list} };
401
402     if ($rows) {
403       $form->{"qty_$i"} = 1 unless $form->parse_amount(\%myconfig, $form->{"qty_$i"});
404
405       if ($rows > 1) {
406
407         select_item(mode => $mode);
408         ::end_of_request();
409
410       } else {
411
412         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
413
414         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
415         $form->{"sellprice_$i"}          = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
416         $form->{"lastcost_$i"}          = $form->format_amount(\%myconfig, $form->{"lastcost_$i"});
417         $form->{"qty_$i"}                = $form->format_amount(\%myconfig, $form->{"qty_$i"});
418       }
419
420       display_form();
421
422     } else {
423
424       # ok, so this is a new part
425       # ask if it is a part or service item
426
427       if (   $form->{"partsgroup_$i"}
428           && ($form->{"partsnumber_$i"} eq "")
429           && ($form->{"description_$i"} eq "")) {
430         $form->{rowcount}--;
431         $form->{"discount_$i"} = "";
432         $form->{"not_discountable_$i"} = "";
433         display_form();
434
435       } else {
436         $form->{"id_$i"}   = 0;
437         new_item();
438       }
439     }
440   }
441
442   $main::lxdebug->leave_sub();
443 }
444
445 sub search {
446   $main::lxdebug->enter_sub();
447
448   check_do_access();
449
450   my $form     = $main::form;
451   my %myconfig = %main::myconfig;
452   my $locale   = $main::locale;
453
454   $form->{vc} = $form->{type} eq 'purchase_delivery_order' ? 'vendor' : 'customer';
455
456   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS",
457                                        "all" => 1 },
458                    "departments"  => "ALL_DEPARTMENTS",
459                    "$form->{vc}s" => "ALL_VC");
460   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
461
462   $form->{SHOW_VC_DROP_DOWN} =  $myconfig{vclimit} > scalar @{ $form->{ALL_VC} };
463   $form->{jsscript}          = 1;
464   $form->{title}             = $locale->text('Delivery Orders');
465
466   $form->header();
467
468   print $form->parse_html_template('do/search');
469
470   $main::lxdebug->leave_sub();
471 }
472
473 sub orders {
474   $main::lxdebug->enter_sub();
475
476   check_do_access();
477
478   my $form     = $main::form;
479   my %myconfig = %main::myconfig;
480   my $locale   = $main::locale;
481   my $cgi      = $::request->{cgi};
482
483   $form->{department_id} = (split /--/, $form->{department})[-1];
484   ($form->{ $form->{vc} }, $form->{"$form->{vc}_id"}) = split(/--/, $form->{ $form->{vc} });
485
486   report_generator_set_default_sort('transdate', 1);
487
488   DO->transactions();
489
490   $form->{rowcount} = scalar @{ $form->{DO} };
491
492   my @columns = qw(
493     ids                     transdate               reqdate
494     id                      donumber
495     ordnumber               customernumber
496     name                    employee  salesman
497     shipvia                 globalprojectnumber
498     transaction_description department
499     open                    delivered
500   );
501
502   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
503   $form->{l_delivered} = "Y"                     if ($form->{delivered} && $form->{notdelivered});
504
505   $form->{title}       = $locale->text('Delivery Orders');
506
507   my $attachment_basename = $form->{vc} eq 'vendor' ? $locale->text('purchase_delivery_order_list') : $locale->text('sales_delivery_order_list');
508
509   my $report = SL::ReportGenerator->new(\%myconfig, $form);
510
511   my @hidden_variables = map { "l_${_}" } @columns;
512   push @hidden_variables, $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered donumber ordnumber
513                                           transaction_description transdatefrom transdateto type vc employee_id salesman_id project_id);
514
515   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
516
517   my %column_defs = (
518     'ids'                     => { 'text' => '', },
519     'transdate'               => { 'text' => $locale->text('Date'), },
520     'reqdate'                 => { 'text' => $locale->text('Reqdate'), },
521     'id'                      => { 'text' => $locale->text('ID'), },
522     'donumber'                => { 'text' => $locale->text('Delivery Order'), },
523     'ordnumber'               => { 'text' => $locale->text('Order'), },
524     'customernumber'          => { 'text' => $locale->text('Customer Number'), },
525     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
526     'employee'                => { 'text' => $locale->text('Employee'), },
527     'salesman'                => { 'text' => $locale->text('Salesman'), },
528     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
529     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
530     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
531     'open'                    => { 'text' => $locale->text('Open'), },
532     'delivered'               => { 'text' => $locale->text('Delivered'), },
533     'department'              => { 'text' => $locale->text('Department'), },
534   );
535
536   foreach my $name (qw(id transdate reqdate donumber ordnumber name employee salesman shipvia transaction_description department)) {
537     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
538     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
539   }
540
541   $form->{"l_type"} = "Y";
542   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
543
544   $column_defs{ids}->{visible} = 'HTML';
545
546   $report->set_columns(%column_defs);
547   $report->set_column_order(@columns);
548
549   $report->set_export_options('orders', @hidden_variables, qw(sort sortdir));
550
551   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
552
553   my @options;
554   if ($form->{customer}) {
555     push @options, $locale->text('Customer') . " : $form->{customer}";
556   }
557   if ($form->{vendor}) {
558     push @options, $locale->text('Vendor') . " : $form->{vendor}";
559   }
560   if ($form->{department}) {
561     my ($department) = split /--/, $form->{department};
562     push @options, $locale->text('Department') . " : $department";
563   }
564   if ($form->{donumber}) {
565     push @options, $locale->text('Delivery Order Number') . " : $form->{donumber}";
566   }
567   if ($form->{ordnumber}) {
568     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
569   }
570   if ($form->{transaction_description}) {
571     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
572   }
573   if ($form->{transdatefrom}) {
574     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
575   }
576   if ($form->{transdateto}) {
577     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
578   }
579   if ($form->{open}) {
580     push @options, $locale->text('Open');
581   }
582   if ($form->{closed}) {
583     push @options, $locale->text('Closed');
584   }
585   if ($form->{delivered}) {
586     push @options, $locale->text('Delivered');
587   }
588   if ($form->{notdelivered}) {
589     push @options, $locale->text('Not delivered');
590   }
591
592   $report->set_options('top_info_text'        => join("\n", @options),
593                        'raw_top_info_text'    => $form->parse_html_template('do/orders_top'),
594                        'raw_bottom_info_text' => $form->parse_html_template('do/orders_bottom'),
595                        'output_format'        => 'HTML',
596                        'title'                => $form->{title},
597                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
598     );
599   $report->set_options_from_form();
600   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
601
602   # add sort and escape callback, this one we use for the add sub
603   $form->{callback} = $href .= "&sort=$form->{sort}";
604
605   # escape callback for href
606   my $callback = $form->escape($href);
607
608   my $edit_url       = build_std_url('action=edit', 'type', 'vc');
609   my $edit_order_url = build_std_url('script=oe.pl', 'type=' . ($form->{type} eq 'sales_delivery_order' ? 'sales_order' : 'purchase_order'), 'action=edit');
610
611   my $idx            = 1;
612
613   foreach my $dord (@{ $form->{DO} }) {
614     $dord->{open}      = $dord->{closed}    ? $locale->text('No')  : $locale->text('Yes');
615     $dord->{delivered} = $dord->{delivered} ? $locale->text('Yes') : $locale->text('No');
616
617     my $row = { map { $_ => { 'data' => $dord->{$_} } } @columns };
618
619     $row->{ids}  = {
620       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $dord->{id})
621                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
622       'valign'   => 'center',
623       'align'    => 'center',
624     };
625
626     $row->{donumber}->{link}  = $edit_url       . "&id=" . E($dord->{id})      . "&callback=${callback}";
627     $row->{ordnumber}->{link} = $edit_order_url . "&id=" . E($dord->{oe_id})   . "&callback=${callback}" if $dord->{oe_id};
628     $report->add_data($row);
629
630     $idx++;
631   }
632
633   $report->generate_with_headers();
634
635   $main::lxdebug->leave_sub();
636 }
637
638 sub save {
639   $main::lxdebug->enter_sub();
640
641   my (%params) = @_;
642
643   check_do_access();
644
645   my $form     = $main::form;
646   my %myconfig = %main::myconfig;
647   my $locale   = $main::locale;
648
649   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
650
651   $form->isblank("transdate", $locale->text('Delivery Order Date missing!'));
652
653   $form->{donumber} =~ s/^\s*//g;
654   $form->{donumber} =~ s/\s*$//g;
655
656   my $msg = ucfirst $form->{vc};
657   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
658
659   # $locale->text('Customer missing!');
660   # $locale->text('Vendor missing!');
661
662   remove_emptied_rows();
663   validate_items();
664
665   # if the name changed get new values
666   if (check_name($form->{vc})) {
667     update();
668     ::end_of_request();
669   }
670
671   $form->{id} = 0 if $form->{saveasnew};
672   # best case fix für bug 1079. Einkaufsrabatt wird nicht richtig
673   # aus Lieferantenauftrag -> Lieferschein -> Rechnung übernommen
674   # Tritt nur auf, wenn man direkt über Lieferschein -> speichern ->
675   # Workflow Rechnung geht (beim Aufruf über edit() i.O.)
676   # Gut. DO-save() speichert den Discount im DB-Format 0.12 für
677   # 12%, die Konvertierung wird leider in $form gemacht und daher
678   # wird die Maske mit dem falschen Rabatt wieder aufgebaut.
679   # Wie immer: backup_vars verwenden um nichts anderes kaputt zu
680   # machen. jan 03.03.2010
681   # nicht mehr notwendig da für bug 1284 der backend aufruf entsprechend
682   # geändert wurde
683   DO->save();
684   # saving the history
685   if(!exists $form->{addition}) {
686     $form->{snumbers} = qq|donumber_| . $form->{donumber};
687     $form->{addition} = "SAVED";
688     $form->save_history;
689   }
690   # /saving the history
691
692   $form->{simple_save} = 1;
693   if (!$params{no_redirect} && !$form->{print_and_save}) {
694     set_headings("edit");
695     update();
696     ::end_of_request();
697   }
698   $main::lxdebug->leave_sub();
699 }
700
701 sub delete {
702   $main::lxdebug->enter_sub();
703
704   check_do_access();
705
706   my $form     = $main::form;
707   my $locale   = $main::locale;
708
709   map { delete $form->{$_} } qw(action header login password);
710   my @variables = map { { 'key' => $_, 'value' => $form->{$_} } } grep { '' eq ref $form->{$_} } keys %{ $form };
711
712   $form->{title} = $locale->text('Delete delivery order');
713   $form->header();
714
715   print $form->parse_html_template('do/delete', { 'VARIABLES' => \@variables });
716
717   $main::lxdebug->leave_sub();
718 }
719
720 sub delete_delivery_order {
721   $main::lxdebug->enter_sub();
722
723   check_do_access();
724
725   my $form     = $main::form;
726   my %myconfig = %main::myconfig;
727   my $locale   = $main::locale;
728
729   if (DO->delete()) {
730     # saving the history
731     if(!exists $form->{addition}) {
732       $form->{snumbers} = qq|donumber_| . $form->{donumber};
733       $form->{addition} = "DELETED";
734       $form->save_history;
735     }
736     # /saving the history
737
738     $form->info($locale->text('Delivery Order deleted!'));
739     ::end_of_request();
740   }
741
742   $form->error($locale->text('Cannot delete delivery order!'));
743
744   $main::lxdebug->leave_sub();
745 }
746
747 sub invoice {
748   $main::lxdebug->enter_sub();
749
750   my $form     = $main::form;
751   my %myconfig = %main::myconfig;
752   my $locale   = $main::locale;
753
754   check_do_access();
755   $main::auth->assert($form->{type} eq 'purchase_delivery_order' ? 'vendor_invoice_edit' : 'invoice_edit');
756
757   $form->{convert_from_do_ids} = $form->{id};
758   $form->{deliverydate}        = $form->{transdate};
759   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
760   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
761   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
762
763   $form->{rowcount}--;
764
765   delete @{$form}{qw(id closed delivered)};
766
767   my ($script, $buysell);
768   if ($form->{type} eq 'purchase_delivery_order') {
769     $form->{title}  = $locale->text('Add Vendor Invoice');
770     $form->{script} = 'ir.pl';
771     $script         = "ir";
772     $buysell        = 'sell';
773
774   } else {
775     $form->{title}  = $locale->text('Add Sales Invoice');
776     $form->{script} = 'is.pl';
777     $script         = "is";
778     $buysell        = 'buy';
779   }
780
781   for my $i (1 .. $form->{rowcount}) {
782     # für bug 1284
783     unless ($form->{"ordnumber"}) {
784       if ($form->{discount}) { # Falls wir einen Lieferanten-/Kundenrabatt haben
785         # und rabattfähig sind, dann
786         unless ($form->{"not_discountable_$i"}) {
787           $form->{"discount_$i"} = $form->{discount}*100; # ... nehmen wir diesen Rabatt
788         }
789       }
790     }
791     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"} } qw(ship qty sellprice listprice lastcost basefactor);
792   }
793
794   $form->{type} = "invoice";
795
796   # locale messages
797   $main::locale = new Locale "$myconfig{countrycode}", "$script";
798   $locale = $main::locale;
799
800   require "bin/mozilla/$form->{script}";
801
802   my $currency = $form->{currency};
803   $form->{shipto} = 1 if $form->{convert_from_do_ids};
804   invoice_links();
805
806   if ($form->{ordnumber}) {
807     require SL::DB::Order;
808     if (my $order = SL::DB::Manager::Order->find_by(ordnumber => $form->{ordnumber})) {
809       $order->load;
810       $form->{orddate} = $order->transdate_as_date;
811       $form->{$_}      = $order->$_ for qw(payment_id salesman_id taxzone_id quonumber);
812     }
813   }
814
815   $form->{currency}     = $currency;
816   $form->{exchangerate} = "";
817   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, $buysell);
818   $form->{exchangerate} = $form->{forex} if ($form->{forex});
819
820   prepare_invoice();
821
822   # format amounts
823   for my $i (1 .. $form->{rowcount}) {
824     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"});
825
826     my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
827     $dec           = length $dec;
828     my $decimalplaces = ($dec > 2) ? $dec : 2;
829
830     # copy delivery date from reqdate for order -> invoice conversion
831     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
832       unless $form->{"deliverydate_$i"};
833
834
835     $form->{"sellprice_$i"} =
836       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
837                            $decimalplaces);
838
839     $form->{"lastcost_$i"} =
840       $form->format_amount(\%myconfig, $form->{"lastcost_$i"},
841                            $decimalplaces);
842
843     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
844     $dec_qty = length $dec_qty;
845     $form->{"qty_$i"} =
846       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
847
848   }
849
850   #  show pricegroup in newly loaded invoice when creating invoice from delivery order
851   for my $i (1 .. $form->{rowcount}) {
852     $form->{"sellprice_pg_$i"} = join '--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"};
853   }
854   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
855   set_pricegroup($_) for 1 .. $form->{rowcount};
856
857   display_form();
858
859   $main::lxdebug->leave_sub();
860 }
861
862 sub invoice_multi {
863   $main::lxdebug->enter_sub();
864
865   my $form     = $main::form;
866   my %myconfig = %main::myconfig;
867   my $locale   = $main::locale;
868
869   check_do_access();
870   $main::auth->assert($form->{type} eq 'sales_delivery_order' ? 'invoice_edit' : 'vendor_invoice_edit');
871
872   my @do_ids = map { $form->{"trans_id_$_"} } grep { $form->{"multi_id_$_"} } (1..$form->{rowcount});
873
874   if (!scalar @do_ids) {
875     $form->show_generic_error($locale->text('You have not selected any delivery order.'), 'back_button' => 1);
876   }
877
878   map { delete $form->{$_} } grep { m/^(?:trans|multi)_id_\d+/ } keys %{ $form };
879
880   if (!DO->retrieve('vc' => $form->{vc}, 'ids' => \@do_ids)) {
881     $form->show_generic_error($form->{vc} eq 'customer' ?
882                               $locale->text('You cannot create an invoice for delivery orders for different customers.') :
883                               $locale->text('You cannot create an invoice for delivery orders from different vendors.'),
884                               'back_button' => 1);
885   }
886
887   my $source_type              = $form->{type};
888   $form->{convert_from_do_ids} = join ' ', @do_ids;
889   # bei der auswahl von mehreren Lieferscheinen fuer eine Rechnung, die einfach in donumber_array
890   # zwischenspeichern (DO.pm) und als ' '-separierte Liste wieder zurueckschreiben
891   # Hinweis: delete gibt den wert zurueck und loescht danach das element (nett und einfach)
892   # $shell: perldoc perlunc; /delete EXPR
893   $form->{donumber}            = delete $form->{donumber_array};
894   $form->{deliverydate}        = $form->{transdate};
895   $form->{transdate}           = $form->current_date(\%myconfig);
896   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
897   $form->{type}                = "invoice";
898   $form->{closed}              = 0;
899   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
900
901   my ($script, $buysell);
902   if ($source_type eq 'purchase_delivery_order') {
903     $form->{title}  = $locale->text('Add Vendor Invoice');
904     $form->{script} = 'ir.pl';
905     $script         = "ir";
906     $buysell        = 'sell';
907
908   } else {
909     $form->{title}  = $locale->text('Add Sales Invoice');
910     $form->{script} = 'is.pl';
911     $script         = "is";
912     $buysell        = 'buy';
913   }
914
915   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
916
917   # get vendor or customer discount
918   my $vc_discount;
919   my $saved_form = save_form();
920   if ($form->{vc} eq 'vendor') {
921     IR->get_vendor(\%myconfig, \%$form);
922     $vc_discount = $form->{vendor_discount};
923   } else {
924     IS->get_customer(\%myconfig, \%$form);
925     $vc_discount = $form->{customer_discount};
926   }
927   restore_form($saved_form);
928
929   $form->{rowcount} = 0;
930   foreach my $ref (@{ $form->{form_details} }) {
931     $form->{rowcount}++;
932     $ref->{reqdate} ||= $ref->{dord_transdate}; # copy transdates into each invoice row
933     map { $form->{"${_}_$form->{rowcount}"} = $ref->{$_} } keys %{ $ref };
934     map { $form->{"${_}_$form->{rowcount}"} = $form->format_amount(\%myconfig, $ref->{$_}) } qw(qty sellprice lastcost);
935
936     if ($vc_discount){ # falls wir einen Lieferanten/Kundenrabatt haben
937       # und keinen anderen discount wert an $i ...
938       $form->{"discount_$form->{rowcount}"} ||= $vc_discount; # ... nehmen wir diesen Rabatt
939     }
940
941     $form->{"discount_$form->{rowcount}"}   = $form->{"discount_$form->{rowcount}"}  * 100; #s.a. Bug 1151
942     # Anm.: Eine Änderung des discounts in der SL/DO.pm->retrieve (select (doi.discount * 100) as discount) ergibt in psql einen
943     # Wert von 10.0000001490116. Ferner ist der Rabatt in der Rechnung dann bei 1.0 (?). Deswegen lasse ich das hier. jb 10.10.09
944
945     $form->{"discount_$form->{rowcount}"} = $form->format_amount(\%myconfig, $form->{"discount_$form->{rowcount}"});
946   }
947   delete $form->{form_details};
948
949   $locale = new Locale "$myconfig{countrycode}", "$script";
950
951   require "bin/mozilla/$form->{script}";
952
953   invoice_links();
954   prepare_invoice();
955
956   #  show pricegroup in newly loaded invoice when creating invoice from delivery order
957   for my $i (1 .. $form->{rowcount}) {
958     $form->{"sellprice_pg_$i"} = join '--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"};
959   }
960   IS->get_pricegroups_for_parts(\%myconfig, \%$form);
961   set_pricegroup($_) for 1 .. $form->{rowcount};
962
963   display_form();
964
965   $main::lxdebug->leave_sub();
966 }
967
968 sub save_as_new {
969   $main::lxdebug->enter_sub();
970
971   check_do_access();
972
973   my $form     = $main::form;
974
975   $form->{saveasnew} = 1;
976   $form->{closed}    = 0;
977   $form->{delivered} = 0;
978   map { delete $form->{$_} } qw(printed emailed queued);
979   delete @{ $form }{ grep { m/^stock_(?:in|out)_\d+/ } keys %{ $form } };
980
981   # Let kivitendo assign a new order number if the user hasn't changed the
982   # previous one. If it has been changed manually then use it as-is.
983   $form->{donumber} =~ s/^\s*//g;
984   $form->{donumber} =~ s/\s*$//g;
985   if ($form->{saved_donumber} && ($form->{saved_donumber} eq $form->{donumber})) {
986     delete($form->{donumber});
987   }
988
989   save();
990
991   $main::lxdebug->leave_sub();
992 }
993
994 sub e_mail {
995   $main::lxdebug->enter_sub();
996
997   check_do_access();
998
999   my $form     = $main::form;
1000
1001   $form->{print_and_save} = 1;
1002
1003   my $saved_form = save_form();
1004
1005   save();
1006
1007   restore_form($saved_form, 0, qw(id ordnumber quonumber));
1008
1009   edit_e_mail();
1010
1011   $main::lxdebug->leave_sub();
1012 }
1013
1014 sub calculate_stock_in_out {
1015   $main::lxdebug->enter_sub();
1016
1017   my $form     = $main::form;
1018
1019   my $i = shift;
1020
1021   if (!$form->{"id_${i}"}) {
1022     $main::lxdebug->leave_sub();
1023     return '';
1024   }
1025
1026   my $all_units = AM->retrieve_all_units();
1027
1028   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
1029   my $sinfo    = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_${i}"});
1030
1031   my $do_qty   = AM->sum_with_unit($::form->{"qty_$i"}, $::form->{"unit_$i"});
1032   my $sum      = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $sinfo });
1033   my $matches  = $do_qty == $sum;
1034
1035   my $content  = $form->format_amount_units('amount'      => $sum * 1,
1036                                             'part_unit'   => $form->{"partunit_$i"},
1037                                             'amount_unit' => $all_units->{$form->{"partunit_$i"}}->{base_unit},
1038                                             'conv_units'  => 'convertible_not_smaller',
1039                                             'max_places'  => 2);
1040   $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="?">|;
1041
1042   $main::lxdebug->leave_sub();
1043
1044   return $content;
1045 }
1046
1047 sub get_basic_bin_wh_info {
1048   $main::lxdebug->enter_sub();
1049
1050   my $stock_info = shift;
1051
1052   my $form     = $main::form;
1053
1054   foreach my $sinfo (@{ $stock_info }) {
1055     next unless ($sinfo->{bin_id});
1056
1057     my $bin_info = WH->get_basic_bin_info('id' => $sinfo->{bin_id});
1058     map { $sinfo->{"${_}_description"} = $sinfo->{"${_}description"} = $bin_info->{"${_}_description"} } qw(bin warehouse);
1059   }
1060
1061   $main::lxdebug->leave_sub();
1062 }
1063
1064 sub stock_in_out_form {
1065   $main::lxdebug->enter_sub();
1066
1067   my $form     = $main::form;
1068
1069   if ($form->{in_out} eq 'out') {
1070     stock_out_form();
1071   } else {
1072     stock_in_form();
1073   }
1074
1075   $main::lxdebug->leave_sub();
1076 }
1077
1078 sub redo_stock_info {
1079   $main::lxdebug->enter_sub();
1080
1081   my %params    = @_;
1082
1083   my $form     = $main::form;
1084
1085   my @non_empty = grep { $_->{qty} } @{ $params{stock_info} };
1086
1087   if ($params{add_empty_row}) {
1088     push @non_empty, {
1089       'warehouse_id' => scalar(@non_empty) ? $non_empty[-1]->{warehouse_id} : undef,
1090       'bin_id'       => scalar(@non_empty) ? $non_empty[-1]->{bin_id}       : undef,
1091     };
1092   }
1093
1094   @{ $params{stock_info} } = @non_empty;
1095
1096   $main::lxdebug->leave_sub();
1097 }
1098
1099 sub update_stock_in {
1100   $main::lxdebug->enter_sub();
1101
1102   my $form     = $main::form;
1103   my %myconfig = %main::myconfig;
1104
1105   my $stock_info = [];
1106
1107   foreach my $i (1..$form->{rowcount}) {
1108     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1109     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber bestbefore qty unit) };
1110   }
1111
1112   display_stock_in_form($stock_info);
1113
1114   $main::lxdebug->leave_sub();
1115 }
1116
1117 sub stock_in_form {
1118   $main::lxdebug->enter_sub();
1119
1120   my $form     = $main::form;
1121
1122   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
1123
1124   display_stock_in_form($stock_info);
1125
1126   $main::lxdebug->leave_sub();
1127 }
1128
1129 sub display_stock_in_form {
1130   $main::lxdebug->enter_sub();
1131
1132   my $stock_info = shift;
1133
1134   my $form     = $main::form;
1135   my %myconfig = %main::myconfig;
1136   my $locale   = $main::locale;
1137
1138   $form->{jsscript} = 1;
1139
1140   $form->{title} = $locale->text('Stock');
1141
1142   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
1143
1144   my $units      = AM->retrieve_units(\%myconfig, $form);
1145   # der zweite Parameter von unit_select_data gibt den default-Namen (selected) vor
1146   my $units_data = AM->unit_select_data($units, $form->{do_unit}, undef, $part_info->{unit});
1147
1148   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
1149                                      'bins'   => 'BINS' });
1150
1151   redo_stock_info('stock_info' => $stock_info, 'add_empty_row' => !$form->{delivered});
1152
1153   get_basic_bin_wh_info($stock_info);
1154
1155   $form->header(no_layout => 1);
1156   print $form->parse_html_template('do/stock_in_form', { 'UNITS'      => $units_data,
1157                                                          'STOCK_INFO' => $stock_info,
1158                                                          'PART_INFO'  => $part_info, });
1159
1160   $main::lxdebug->leave_sub();
1161 }
1162
1163 sub _stock_in_out_set_qty_display {
1164   my $stock_info       = shift;
1165   my $form             = $::form;
1166   my $all_units        = AM->retrieve_all_units();
1167   my $sum              = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $stock_info });
1168   $form->{qty_display} = $form->format_amount_units(amount      => $sum * 1,
1169                                                     part_unit   => $form->{partunit},
1170                                                     amount_unit => $all_units->{ $form->{partunit} }->{base_unit},
1171                                                     conv_units  => 'convertible_not_smaller',
1172                                                     max_places  => 2);
1173 }
1174
1175 sub set_stock_in {
1176   $main::lxdebug->enter_sub();
1177
1178   my $form     = $main::form;
1179   my %myconfig = %main::myconfig;
1180
1181   my $stock_info = [];
1182
1183   foreach my $i (1..$form->{rowcount}) {
1184     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1185
1186     next if ($form->{"qty_$i"} <= 0);
1187
1188     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber bestbefore qty unit) };
1189   }
1190
1191   $form->{stock} = YAML::Dump($stock_info);
1192
1193   _stock_in_out_set_qty_display($stock_info);
1194
1195   my $do_qty       = AM->sum_with_unit($::form->parse_amount(\%::myconfig, $::form->{do_qty}), $::form->{do_unit});
1196   my $transfer_qty = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $stock_info });
1197
1198   $form->header();
1199   print $form->parse_html_template('do/set_stock_in_out', {
1200     qty_matches => $do_qty == $transfer_qty,
1201   });
1202
1203   $main::lxdebug->leave_sub();
1204 }
1205
1206 sub stock_out_form {
1207   $main::lxdebug->enter_sub();
1208
1209   my $form     = $main::form;
1210   my %myconfig = %main::myconfig;
1211   my $locale   = $main::locale;
1212
1213   $form->{title} = $locale->text('Release From Stock');
1214
1215   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
1216
1217   my $units      = AM->retrieve_units(\%myconfig, $form);
1218   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
1219
1220   my @contents   = DO->get_item_availability('parts_id' => $form->{parts_id});
1221
1222   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
1223
1224   if (!$form->{delivered}) {
1225     foreach my $row (@contents) {
1226       $row->{available_qty} = $form->format_amount_units('amount'      => $row->{qty} * 1,
1227                                                          'part_unit'   => $part_info->{unit},
1228                                                          'conv_units'  => 'convertible_not_smaller',
1229                                                          'max_places'  => 2);
1230
1231       foreach my $sinfo (@{ $stock_info }) {
1232         next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
1233                  ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1234                  ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
1235                  ($row->{bestbefore}   ne $sinfo->{bestbefore}));
1236
1237         map { $row->{"stock_$_"} = $sinfo->{$_} } qw(qty unit error);
1238       }
1239     }
1240
1241   } else {
1242     get_basic_bin_wh_info($stock_info);
1243
1244     foreach my $sinfo (@{ $stock_info }) {
1245       map { $sinfo->{"stock_$_"} = $sinfo->{$_} } qw(qty unit);
1246     }
1247   }
1248
1249   $form->header(no_layout => 1);
1250   print $form->parse_html_template('do/stock_out_form', { 'UNITS'      => $units_data,
1251                                                           'WHCONTENTS' => $form->{delivered} ? $stock_info : \@contents,
1252                                                           'PART_INFO'  => $part_info, });
1253
1254   $main::lxdebug->leave_sub();
1255 }
1256
1257 sub set_stock_out {
1258   $main::lxdebug->enter_sub();
1259
1260   my $form     = $main::form;
1261   my %myconfig = %main::myconfig;
1262   my $locale   = $main::locale;
1263
1264   my $stock_info = [];
1265
1266   foreach my $i (1 .. $form->{rowcount}) {
1267     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1268
1269     next if ($form->{"qty_$i"} <= 0);
1270
1271     push @{ $stock_info }, {
1272       'warehouse_id' => $form->{"warehouse_id_$i"},
1273       'bin_id'       => $form->{"bin_id_$i"},
1274       'chargenumber' => $form->{"chargenumber_$i"},
1275       'bestbefore'   => $form->{"bestbefore_$i"},
1276       'qty'          => $form->{"qty_$i"},
1277       'unit'         => $form->{"unit_$i"},
1278       'row'          => $i,
1279     };
1280   }
1281
1282   my @errors     = DO->check_stock_availability('requests' => $stock_info,
1283                                                 'parts_id' => $form->{parts_id});
1284
1285   $form->{stock} = YAML::Dump($stock_info);
1286
1287   if (@errors) {
1288     $form->{ERRORS} = [];
1289     map { push @{ $form->{ERRORS} }, $locale->text('Error in row #1: The quantity you entered is bigger than the stocked quantity.', $_->{row}); } @errors;
1290     stock_in_out_form();
1291
1292   } else {
1293     _stock_in_out_set_qty_display($stock_info);
1294
1295     my $do_qty       = AM->sum_with_unit($::form->parse_amount(\%::myconfig, $::form->{do_qty}), $::form->{do_unit});
1296     my $transfer_qty = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $stock_info });
1297
1298     $form->header();
1299     print $form->parse_html_template('do/set_stock_in_out', {
1300       qty_matches => $do_qty == $transfer_qty,
1301     });
1302   }
1303
1304   $main::lxdebug->leave_sub();
1305 }
1306
1307 sub transfer_in {
1308   $main::lxdebug->enter_sub();
1309
1310   my $form     = $main::form;
1311   my %myconfig = %main::myconfig;
1312   my $locale   = $main::locale;
1313
1314   if ($form->{id} && DO->is_marked_as_delivered(id => $form->{id})) {
1315     $form->show_generic_error($locale->text('The parts for this delivery order have already been transferred in.'), 'back_button' => 1);
1316   }
1317
1318   save(no_redirect => 1);
1319
1320   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_in_${_}"} } (1 .. $form->{rowcount});
1321   my @all_requests;
1322
1323   if (@part_ids) {
1324     my $units         = AM->retrieve_units(\%myconfig, $form);
1325     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1326     my %request_map;
1327
1328     $form->{ERRORS}   = [];
1329
1330     foreach my $i (1 .. $form->{rowcount}) {
1331       next unless ($form->{"id_$i"} && $form->{"stock_in_$i"});
1332
1333       my $row_sum_base_qty = 0;
1334       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1335
1336       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_in_$i"}) }) {
1337         $request->{parts_id}  = $form->{"id_$i"};
1338         $row_sum_base_qty    += $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1339
1340         push @all_requests, $request;
1341       }
1342
1343       next if (0 == $row_sum_base_qty);
1344
1345       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1346
1347 #      if ($do_base_qty != $row_sum_base_qty) {
1348 #        push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no stock at all or the full quantity of #2 #3.',
1349 #                                                 $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1350 #      }
1351     }
1352
1353     if (@{ $form->{ERRORS} }) {
1354       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been marked as delivered. The warehouse contents have not changed.');
1355
1356       set_headings('edit');
1357       update();
1358       $main::lxdebug->leave_sub();
1359
1360       ::end_of_request();
1361     }
1362   }
1363
1364   DO->transfer_in_out('direction' => 'in',
1365                       'requests'  => \@all_requests);
1366
1367   SL::DB::DeliveryOrder->new(id => $form->{id})->load->update_attributes(delivered => 1);
1368
1369   $form->{callback} = 'do.pl?action=edit&type=purchase_delivery_order&id=' . $form->escape($form->{id});
1370   $form->redirect;
1371
1372   $main::lxdebug->leave_sub();
1373 }
1374
1375 sub transfer_out {
1376   $main::lxdebug->enter_sub();
1377
1378   my $form     = $main::form;
1379   my %myconfig = %main::myconfig;
1380   my $locale   = $main::locale;
1381
1382   if ($form->{id} && DO->is_marked_as_delivered(id => $form->{id})) {
1383     $form->show_generic_error($locale->text('The parts for this delivery order have already been transferred out.'), 'back_button' => 1);
1384   }
1385
1386   save(no_redirect => 1);
1387
1388   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_out_${_}"} } (1 .. $form->{rowcount});
1389   my @all_requests;
1390
1391   if (@part_ids) {
1392     my $units         = AM->retrieve_units(\%myconfig, $form);
1393     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1394     my %request_map;
1395
1396     $form->{ERRORS}   = [];
1397
1398     foreach my $i (1 .. $form->{rowcount}) {
1399       next unless ($form->{"id_$i"} && $form->{"stock_out_$i"});
1400
1401       my $row_sum_base_qty = 0;
1402       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1403
1404       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_out_$i"}) }) {
1405         $request->{parts_id} = $form->{"id_$i"};
1406         $request->{base_qty} = $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1407         $request->{project_id} = $form->{"project_id_$i"} ? $form->{"project_id_$i"} : $form->{globalproject_id};
1408
1409         my $map_key          = join '--', ($form->{"id_$i"}, @{$request}{qw(warehouse_id bin_id chargenumber bestbefore)});
1410
1411         $request_map{$map_key}                 ||= $request;
1412         $request_map{$map_key}->{sum_base_qty} ||= 0;
1413         $request_map{$map_key}->{sum_base_qty}  += $request->{base_qty};
1414         $row_sum_base_qty                       += $request->{base_qty};
1415
1416         push @all_requests, $request;
1417       }
1418
1419       next if (0 == $row_sum_base_qty);
1420
1421       my $do_base_qty = $form->{"qty_$i"} * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1422
1423 #      if ($do_base_qty != $row_sum_base_qty) {
1424 #        push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no transfer at all or the full quantity of #2 #3.',
1425 #                                                 $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1426 #      }
1427     }
1428
1429     if (%request_map) {
1430       my @bin_ids      = map { $_->{bin_id} } values %request_map;
1431       my %bin_info_map = WH->get_basic_bin_info('id' => \@bin_ids);
1432       my @contents     = DO->get_item_availability('parts_id' => \@part_ids);
1433
1434       foreach my $inv (@contents) {
1435         my $map_key = join '--', @{$inv}{qw(parts_id warehouse_id bin_id chargenumber bestbefore)};
1436
1437         next unless ($request_map{$map_key});
1438
1439         my $request    = $request_map{$map_key};
1440         $request->{ok} = $request->{sum_base_qty} <= $inv->{qty};
1441       }
1442
1443       foreach my $request (values %request_map) {
1444         next if ($request->{ok});
1445
1446         my $pinfo = $part_info_map{$request->{parts_id}};
1447         my $binfo = $bin_info_map{$request->{bin_id}};
1448
1449         if ($::instance_conf->get_show_bestbefore) {
1450             push @{ $form->{ERRORS} }, $locale->text("There is not enough available of '#1' at warehouse '#2', bin '#3', #4, #5, for the transfer of #6.",
1451                                                      $pinfo->{description},
1452                                                      $binfo->{warehouse_description},
1453                                                      $binfo->{bin_description},
1454                                                      $request->{chargenumber} ? $locale->text('chargenumber #1', $request->{chargenumber}) : $locale->text('no chargenumber'),
1455                                                      $request->{bestbefore} ? $locale->text('bestbefore #1', $request->{bestbefore}) : $locale->text('no bestbefore'),
1456                                                      $form->format_amount_units('amount'      => $request->{sum_base_qty},
1457                                                                                 'part_unit'   => $pinfo->{unit},
1458                                                                                 'conv_units'  => 'convertible_not_smaller'));
1459         } else {
1460             push @{ $form->{ERRORS} }, $locale->text("There is not enough available of '#1' at warehouse '#2', bin '#3', #4, for the transfer of #5.",
1461                                                      $pinfo->{description},
1462                                                      $binfo->{warehouse_description},
1463                                                      $binfo->{bin_description},
1464                                                      $request->{chargenumber} ? $locale->text('chargenumber #1', $request->{chargenumber}) : $locale->text('no chargenumber'),
1465                                                      $form->format_amount_units('amount'      => $request->{sum_base_qty},
1466                                                                                 'part_unit'   => $pinfo->{unit},
1467                                                                                 'conv_units'  => 'convertible_not_smaller'));
1468         }
1469       }
1470     }
1471
1472     if (@{ $form->{ERRORS} }) {
1473       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been marked as delivered. The warehouse contents have not changed.');
1474
1475       set_headings('edit');
1476       update();
1477       $main::lxdebug->leave_sub();
1478
1479       ::end_of_request();
1480     }
1481   }
1482   DO->transfer_in_out('direction' => 'out',
1483                       'requests'  => \@all_requests);
1484
1485   SL::DB::DeliveryOrder->new(id => $form->{id})->load->update_attributes(delivered => 1);
1486
1487   $form->{callback} = 'do.pl?action=edit&type=sales_delivery_order&id=' . $form->escape($form->{id});
1488   $form->redirect;
1489
1490   $main::lxdebug->leave_sub();
1491 }
1492
1493 sub mark_closed {
1494   $main::lxdebug->enter_sub();
1495
1496   my $form     = $main::form;
1497
1498   DO->close_orders('ids' => [ $form->{id} ]);
1499
1500   $form->{closed} = 1;
1501
1502   update();
1503
1504   $main::lxdebug->leave_sub();
1505 }
1506
1507
1508 sub yes {
1509   call_sub($main::form->{yes_nextsub});
1510 }
1511
1512 sub no {
1513   call_sub($main::form->{no_nextsub});
1514 }
1515
1516 sub update {
1517   call_sub($main::form->{update_nextsub} || $main::form->{nextsub} || 'update_delivery_order');
1518 }
1519
1520 sub dispatcher {
1521   my $form     = $main::form;
1522   my $locale   = $main::locale;
1523
1524   foreach my $action (qw(update ship_to print e_mail save transfer_out transfer_out_default
1525                          transfer_in transfer_in_default mark_closed save_as_new invoice delete)) {
1526     if ($form->{"action_${action}"}) {
1527       call_sub($action);
1528       return;
1529     }
1530   }
1531
1532   $form->error($locale->text('No action defined.'));
1533 }
1534
1535 sub transfer_out_default {
1536   $main::lxdebug->enter_sub();
1537
1538   my $form     = $main::form;
1539
1540   transfer_in_out_default('direction' => 'out');
1541
1542   $main::lxdebug->leave_sub();
1543 }
1544
1545 sub transfer_in_default {
1546   $main::lxdebug->enter_sub();
1547
1548   my $form     = $main::form;
1549
1550   transfer_in_out_default('direction' => 'in');
1551
1552   $main::lxdebug->leave_sub();
1553 }
1554
1555 # Falls das Standardlagerverfahren aktiv ist, wird
1556 # geprüft, ob alle Standardlagerplätze für die Auslager-
1557 # artikel vorhanden sind UND ob die Warenmenge ausreicht zum
1558 # Auslagern. Falls nicht wird entsprechend eine Fehlermeldung
1559 # generiert. Offen Chargennummer / bestbefore wird nicht berücksichtigt
1560 sub transfer_in_out_default {
1561   $main::lxdebug->enter_sub();
1562
1563   my $form     = $main::form;
1564   my %myconfig = %main::myconfig;
1565   my $locale   = $main::locale;
1566   my %params   = @_;
1567
1568   my (%missing_default_bins, %qty_parts, @all_requests, %part_info_map, $default_warehouse_id, $default_bin_id);
1569
1570   Common::check_params(\%params, qw(direction));
1571
1572   # entsprechende defaults holen, falls standardlagerplatz verwendet werden soll
1573   if ($::instance_conf->get_transfer_default_use_master_default_bin) {
1574     $default_warehouse_id = $::instance_conf->get_default_warehouse_id;
1575     $default_bin_id       = $::instance_conf->get_default_bin_id;
1576   }
1577
1578
1579   my @part_ids = map { $form->{"id_${_}"} } (1 .. $form->{rowcount});
1580   if (@part_ids) {
1581     my $units         = AM->retrieve_units(\%myconfig, $form);
1582     %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1583     foreach my $i (1 .. $form->{rowcount}) {
1584       next unless ($form->{"id_$i"});
1585       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1586       my $qty =   $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1587       $qty_parts{$form->{"id_$i"}} += $qty;
1588
1589
1590       $part_info_map{$form->{"id_$i"}}{bin_id}       ||= $default_bin_id;
1591       $part_info_map{$form->{"id_$i"}}{warehouse_id} ||= $default_warehouse_id;
1592
1593       push @all_requests, {
1594                         'chargenumber' => '',  #?? die müsste entsprechend geholt werden
1595                         #'bestbefore' => undef, # TODO wird nicht berücksichtigt
1596                         'bin_id' => $part_info_map{$form->{"id_$i"}}{bin_id},
1597                         'qty' => $qty,
1598                         'parts_id' => $form->{"id_$i"},
1599                         'comment' => 'Default transfer DO',
1600                         'ok' => 1,
1601                         'unit' => $part_info_map{$form->{"id_$i"}}{unit},
1602                         'warehouse_id' => $part_info_map{$form->{"id_$i"}}{warehouse_id},
1603                         'oe_id' => $form->{id},
1604                         'project_id' => $form->{"project_id_$i"} ? $form->{"project_id_$i"} : $form->{globalproject_id}
1605                       };
1606     }
1607
1608     # jetzt wird erst überprüft, ob die Stückzahl entsprechend stimmt.
1609     if ($params{direction} eq 'out') {  # wird nur für ausgehende Mengen benötigit
1610       foreach my $key (keys %qty_parts) {
1611
1612         $missing_default_bins{$key}{missing_bin} = 1 unless ($part_info_map{$key}{bin_id});
1613         next unless ($part_info_map{$key}{bin_id}); # abbruch
1614
1615         my ($max_qty, $error) = WH->get_max_qty_parts_bin(parts_id => $key, bin_id => $part_info_map{$key}{bin_id});
1616         if ($error == 1) {
1617           # wir können nicht entscheiden, welche charge oder mhd (bestbefore) ausgewählt sein soll
1618           # deshalb rückmeldung nach oben geben, manuell auszulagern
1619           # TODO Bei nur einem Treffer mit Charge oder bestbefore wäre das noch möglich
1620           $missing_default_bins{$key}{chargenumber} = 1;
1621         }
1622         if ($max_qty < $qty_parts{$key}){
1623           $missing_default_bins{$key}{missing_qty} = $max_qty - $qty_parts{$key};
1624         }
1625       }
1626     }
1627   } # if @parts_id
1628
1629   # Abfrage für Fehlerbehandlung (nur bei direction == out)
1630   if (scalar (keys %missing_default_bins)) {
1631     my $fehlertext;
1632     foreach my $fehler (keys %missing_default_bins) {
1633
1634       my $ware = WH->get_part_description(parts_id => $fehler);
1635       if ($missing_default_bins{$fehler}{missing_bin}){
1636         $fehlertext .= "Kein Standardlagerplatz definiert bei $ware <br>";
1637       }
1638       if ($missing_default_bins{$fehler}{missing_qty}) {  # missing_qty
1639         $fehlertext .= "Es fehlen " . $missing_default_bins{$fehler}{missing_qty}*-1 .
1640                        " von $ware auf dem Standard-Lagerplatz " . $part_info_map{$fehler}{bin} .   " zum Auslagern<br>";
1641       }
1642       if ($missing_default_bins{$fehler}{chargenumber}){
1643         $fehlertext .= "Die Ware hat eine Chargennummer oder eine Mindesthaltbarkeit definiert.
1644                         Hier kann man nicht automatisch entscheiden.
1645                         Bitte diesen Lieferschein manuell auslagern.
1646                         Bei: $ware";
1647       }
1648       # auslagern soll immer gehen, auch wenn nicht genügend auf lager ist.
1649       # der lagerplatz ist hier extra konfigurierbar, bspw. Lager-Korrektur mit
1650       # Lagerplatz Lagerplatz-Korrektur
1651       my $default_warehouse_id_ignore_onhand = $::instance_conf->get_default_warehouse_id_ignore_onhand;
1652       my $default_bin_id_ignore_onhand       = $::instance_conf->get_default_bin_id_ignore_onhand;
1653       if ($::instance_conf->get_transfer_default_ignore_onhand && $default_bin_id_ignore_onhand) {
1654         # entsprechende defaults holen
1655         # falls chargenumber, bestbefore oder anzahl nicht stimmt, auf automatischen
1656         # lagerplatz wegbuchen!
1657         foreach (@all_requests) {
1658           if ($_->{parts_id} eq $fehler){
1659           $_->{bin_id}        = $default_bin_id_ignore_onhand;
1660           $_->{warehouse_id}  = $default_warehouse_id_ignore_onhand;
1661           }
1662         }
1663       } else {
1664         #$main::lxdebug->message(0, 'Fehlertext: ' . $fehlertext);
1665         $form->show_generic_error($locale->text("Cannot transfer. <br> Reason:<br>#1", $fehlertext ), 'back_button' => 1);
1666       }
1667     }
1668   }
1669
1670
1671   # hier der eigentliche fallunterschied für in oder out
1672   my $prefix   = $params{direction} eq 'in' ? 'in' : 'out';
1673
1674   # dieser array_ref ist für DO->save da:
1675   # einmal die all_requests in YAML verwandeln, damit delivery_order_items_stock
1676   # gefüllt werden kann.
1677   my $i = 1;
1678   foreach (@all_requests){
1679     $form->{"stock_${prefix}_$i"} = YAML::Dump([$_]);
1680     $i++;
1681   }
1682
1683   save(no_redirect => 1); # Wir können auslagern, deshalb beleg speichern
1684                           # und in delivery_order_items_stock speichern
1685   DO->transfer_in_out('direction' => $prefix,
1686                       'requests'  => \@all_requests);
1687
1688   SL::DB::DeliveryOrder->new(id => $form->{id})->load->update_attributes(delivered => 1);
1689
1690   $form->{callback} = 'do.pl?action=edit&type=sales_delivery_order&id=' . $form->escape($form->{id}) if $params{direction} eq 'out';
1691   $form->{callback} = 'do.pl?action=edit&type=purchase_delivery_order&id=' . $form->escape($form->{id}) if $params{direction} eq 'in';
1692   $form->redirect;
1693
1694 }