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