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