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