7f83bf399b7398b0083096116fd3ae7819e96863
[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::DO;
38 use SL::IR;
39 use SL::IS;
40 use SL::ReportGenerator;
41 use SL::WH;
42
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/common.pl";
45 require "bin/mozilla/invoice_io.pl";
46 require "bin/mozilla/io.pl";
47 require "bin/mozilla/reportgenerator.pl";
48
49 1;
50
51 # end of main
52
53 sub check_do_access {
54   $auth->assert($form->{type} . '_edit');
55 }
56
57 sub set_headings {
58   $lxdebug->enter_sub();
59
60   check_do_access();
61
62   my ($action) = @_;
63
64   if ($form->{type} eq 'purchase_delivery_order') {
65     $form->{vc}    = 'vendor';
66     $form->{title} = $action eq "edit" ? $locale->text('Edit Purchase Delivery Order') : $locale->text('Add Purchase Delivery Order');
67   } else {
68     $form->{vc}    = 'customer';
69     $form->{title} = $action eq "edit" ? $locale->text('Edit Sales Delivery Order') : $locale->text('Add Sales Delivery Order');
70   }
71
72   $form->{heading} = $locale->text('Delivery Order');
73
74   $lxdebug->leave_sub();
75 }
76
77 sub add {
78   $lxdebug->enter_sub();
79
80   check_do_access();
81
82   set_headings("add");
83
84   $form->{callback} = build_std_url('action=add', 'type', 'vc') unless ($form->{callback});
85
86   order_links();
87   prepare_order();
88   display_form();
89
90   $lxdebug->leave_sub();
91 }
92
93 sub edit {
94   $lxdebug->enter_sub();
95
96   check_do_access();
97
98   # show history button
99   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
100   #/show hhistory button
101
102   $form->{simple_save} = 0;
103
104   set_headings("edit");
105
106   # editing without stuff to edit? try adding it first
107   if ($form->{rowcount} && !$form->{print_and_save}) {
108 #     map { $id++ if $form->{"multi_id_$_"} } (1 .. $form->{rowcount});
109 #     if (!$id) {
110
111       # reset rowcount
112       undef $form->{rowcount};
113       add();
114       $lxdebug->leave_sub();
115       return;
116 #     }
117   } elsif (!$form->{id}) {
118     add();
119     $lxdebug->leave_sub();
120     return;
121   }
122
123   if ($form->{print_and_save}) {
124     $form->{action}   = "dispatcher";
125     $form->{action_print} = "1";
126     $form->{resubmit} = 1;
127     $language_id      = $form->{language_id};
128     $printer_id       = $form->{printer_id};
129   }
130
131   set_headings("edit");
132
133   order_links();
134   prepare_order();
135
136   if ($form->{print_and_save}) {
137     $form->{language_id} = $language_id;
138     $form->{printer_id}  = $printer_id;
139   }
140
141   display_form();
142
143   $lxdebug->leave_sub();
144 }
145
146 sub order_links {
147   $lxdebug->enter_sub();
148
149   check_do_access();
150
151   # get customer/vendor
152   $form->all_vc(\%myconfig, $form->{vc}, ($form->{vc} eq 'customer') ? "AR" : "AP");
153
154   # retrieve order/quotation
155   $form->{webdav}   = $webdav;
156   $form->{jsscript} = 1;
157
158   my $editing = $form->{id};
159
160   DO->retrieve('vc'  => $form->{vc},
161                'ids' => $form->{id});
162
163   $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id taxincluded cp_id intnotes));
164   $form->{shipto} = 1 if $form->{id};
165
166   # get customer / vendor
167   if ($form->{vc} eq 'vendor') {
168     IR->get_vendor(\%myconfig, \%$form);
169   } else {
170     IS->get_customer(\%myconfig, \%$form);
171   }
172
173   $form->restore_vars(qw(payment_id language_id taxzone_id intnotes cp_id));
174   $form->restore_vars(qw(taxincluded)) if $form->{id};
175   $form->restore_vars(qw(salesman_id)) if $editing;
176
177   if ($form->{"all_$form->{vc}"}) {
178     unless ($form->{"$form->{vc}_id"}) {
179       $form->{"$form->{vc}_id"} = $form->{"all_$form->{vc}"}->[0]->{id};
180     }
181   }
182
183   ($form->{ $form->{vc} })  = split /--/, $form->{ $form->{vc} };
184   $form->{"old$form->{vc}"} = qq|$form->{$form->{vc}}--$form->{"$form->{vc}_id"}|;
185
186   $form->{employee} = "$form->{employee}--$form->{employee_id}";
187
188   $lxdebug->leave_sub();
189 }
190
191 sub prepare_order {
192   $lxdebug->enter_sub();
193
194   check_do_access();
195
196   $form->{formname} = $form->{type} unless $form->{formname};
197
198   my $i = 0;
199   foreach $ref (@{ $form->{form_details} }) {
200     $form->{rowcount} = ++$i;
201
202     map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
203   }
204   for my $i (1 .. $form->{rowcount}) {
205     if ($form->{id}) {
206       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
207     } else {
208       $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"});
209     }
210     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
211     $dec           = length $dec;
212     $decimalplaces = ($dec > 2) ? $dec : 2;
213
214     # copy reqdate from deliverydate for invoice -> order conversion
215     $form->{"reqdate_$i"} = $form->{"deliverydate_$i"} unless $form->{"reqdate_$i"};
216
217     $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
218
219     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
220     $dec_qty = length $dec_qty;
221     $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
222   }
223
224   $lxdebug->leave_sub();
225 }
226
227 sub form_header {
228   $lxdebug->enter_sub();
229
230   check_do_access();
231
232   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
233   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
234
235   # use JavaScript Calendar or not
236   $form->{jsscript} = 1;
237
238   #write Trigger
239   $jsscript = Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1", "reqdate", "BL", "trigger2");
240
241   my @old_project_ids = ($form->{"globalproject_id"});
242   map({ push(@old_project_ids, $form->{"project_id_$_"})
243           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
244
245   my $vc = $form->{vc} eq "customer" ? "customers" : "vendors";
246   $form->get_lists("contacts"       => "ALL_CONTACTS",
247                    "shipto"         => "ALL_SHIPTO",
248                    "projects"       => {
249                      "key"          => "ALL_PROJECTS",
250                      "all"          => 0,
251                      "old_id"       => \@old_project_ids
252                    },
253                    "employees"      => "ALL_EMPLOYEES",
254                    "salesmen"       => "ALL_SALESMEN",
255                    $vc              => "ALL_VC",
256                    "price_factors"  => "ALL_PRICE_FACTORS",
257                    "departments"    => "ALL_DEPARTMENTS",
258                    "business_types" => "ALL_BUSINESS_TYPES",
259     );
260
261   map { $_->{value} = "$_->{description}--$_->{id}" } @{ $form->{ALL_DEPARTMENTS} };
262   map { $_->{value} = "$_->{name}--$_->{id}"        } @{ $form->{ALL_VC} };
263
264   $form->{SHOW_VC_DROP_DOWN} =  $myconfig{vclimit} > scalar @{ $form->{ALL_VC} };
265
266   $form->{oldvcname}         =  $form->{"old$form->{vc}"};
267   $form->{oldvcname}         =~ s/--.*//;
268
269   $form->{onload} = "";
270   if ($form->{resubmit}) {
271     if ($form->{format} eq "html") {
272       $form->{onload} = "window.open('about:blank','Beleg'); document.do.target = 'Beleg';";
273     }
274     # emulate click for resubmitting actions
275     $form->{onload} .= "document.do.${_}.click(); " for grep { /^action_/ } keys %$form;
276     $form->{onload} .= "document.do.submit();"
277   }
278
279   $form->header();
280   # Fix für Bug 1082 Erwartet wird: 'abteilungsNAME--abteilungsID'
281   $form->{department} .= '--' . $form->{department_id};
282
283   print $form->parse_html_template('do/form_header');
284
285   $lxdebug->leave_sub();
286 }
287
288 sub form_footer {
289   $lxdebug->enter_sub();
290
291   check_do_access();
292
293   $form->{PRINT_OPTIONS} = print_options('inline' => 1);
294
295   print $form->parse_html_template('do/form_footer');
296
297   $lxdebug->leave_sub();
298 }
299
300 sub update_delivery_order {
301   $lxdebug->enter_sub();
302
303   check_do_access();
304
305   set_headings($form->{"id"} ? "edit" : "add");
306
307   $form->{update} = 1;
308
309   $payment_id = $form->{payment_id} if $form->{payment_id};
310
311   check_name($form->{vc});
312
313   $form->{payment_id} = $payment_id if $form->{payment_id} eq "";
314
315   # for pricegroups
316   $i = $form->{rowcount};
317
318   if (   ($form->{"partnumber_$i"} eq "")
319       && ($form->{"description_$i"} eq "")
320       && ($form->{"partsgroup_$i"}  eq "")) {
321
322     check_form();
323
324   } else {
325
326     if ($form->{type} eq 'purchase_delivery_order') {
327       IR->retrieve_item(\%myconfig, $form);
328     } else {
329       IS->retrieve_item(\%myconfig, $form);
330     }
331
332     my $rows = scalar @{ $form->{item_list} };
333
334     if ($rows) {
335       $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
336
337       if ($rows > 1) {
338
339         select_item();
340         exit;
341
342       } else {
343
344         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
345
346         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
347         $form->{"sellprice_$i"}          = $form->format_amount(\%myconfig, $form->{"sellprice_$i"});
348         $form->{"qty_$i"}                = $form->format_amount(\%myconfig, $form->{"qty_$i"});
349       }
350
351       display_form();
352
353     } else {
354
355       # ok, so this is a new part
356       # ask if it is a part or service item
357
358       if (   $form->{"partsgroup_$i"}
359           && ($form->{"partsnumber_$i"} eq "")
360           && ($form->{"description_$i"} eq "")) {
361         $form->{rowcount}--;
362         $form->{"discount_$i"} = "";
363         display_form();
364
365       } else {
366         $form->{"id_$i"}   = 0;
367         new_item();
368       }
369     }
370   }
371
372   $lxdebug->leave_sub();
373 }
374
375 sub search {
376   $lxdebug->enter_sub();
377
378   check_do_access();
379
380   $form->{vc} = $form->{type} eq 'purchase_delivery_order' ? 'vendor' : 'customer';
381
382   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS",
383                                        "all" => 1 },
384                    "employees"    => "ALL_EMPLOYEES",
385                    "salesmen"     => "ALL_SALESMEN",
386                    "$form->{vc}s" => "ALL_VC");
387
388   $form->{SHOW_VC_DROP_DOWN} =  $myconfig{vclimit} > scalar @{ $form->{ALL_VC} };
389   $form->{jsscript}          = 1;
390   $form->{title}             = $locale->text('Delivery Orders');
391
392   $form->header();
393
394   print $form->parse_html_template('do/search');
395
396   $lxdebug->leave_sub();
397 }
398
399 sub orders {
400   $lxdebug->enter_sub();
401
402   check_do_access();
403
404   ($form->{ $form->{vc} }, $form->{"${form->{vc}}_id"}) = split(/--/, $form->{ $form->{vc} });
405
406   report_generator_set_default_sort('transdate', 1);
407
408   DO->transactions();
409
410   $form->{rowcount} = scalar @{ $form->{DO} };
411
412   my @columns = qw(
413     ids                     transdate
414     id                      donumber
415     ordnumber
416     name                    employee
417     shipvia                 globalprojectnumber
418     transaction_description
419     open                    delivered
420   );
421
422   $form->{l_open}      = $form->{l_closed} = "Y" if ($form->{open}      && $form->{closed});
423   $form->{l_delivered} = "Y"                     if ($form->{delivered} && $form->{notdelivered});
424
425   $form->{title}       = $locale->text('Delivery Orders');
426
427   my $attachment_basename = $form->{vc} eq 'vendor' ? $locale->text('purchase_delivery_order_list') : $locale->text('sales_delivery_order_list');
428
429   my $report = SL::ReportGenerator->new(\%myconfig, $form);
430
431   my @hidden_variables = map { "l_${_}" } @columns;
432   push @hidden_variables, $form->{vc}, qw(l_closed l_notdelivered open closed delivered notdelivered donumber ordnumber
433                                           transaction_description transdatefrom transdateto type vc employee_id salesman_id);
434
435   my $href = build_std_url('action=orders', grep { $form->{$_} } @hidden_variables);
436
437   my %column_defs = (
438     'ids'                     => { 'text' => '', },
439     'transdate'               => { 'text' => $locale->text('Date'), },
440     'id'                      => { 'text' => $locale->text('ID'), },
441     'donumber'                => { 'text' => $locale->text('Delivery Order'), },
442     'ordnumber'               => { 'text' => $locale->text('Order'), },
443     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
444     'employee'                => { 'text' => $locale->text('Salesperson'), },
445     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
446     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
447     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
448     'open'                    => { 'text' => $locale->text('Open'), },
449     'delivered'               => { 'text' => $locale->text('Delivered'), },
450   );
451
452   foreach my $name (qw(id transdate donumber ordnumber name employee shipvia transaction_description)) {
453     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
454     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
455   }
456
457   $form->{"l_type"} = "Y";
458   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
459
460   $column_defs{ids}->{visible} = 'HTML';
461
462   $report->set_columns(%column_defs);
463   $report->set_column_order(@columns);
464
465   $report->set_export_options('orders', @hidden_variables, qw(sort sortdir));
466
467   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
468
469   my @options;
470   if ($form->{customer}) {
471     push @options, $locale->text('Customer') . " : $form->{customer}";
472   }
473   if ($form->{vendor}) {
474     push @options, $locale->text('Vendor') . " : $form->{vendor}";
475   }
476   if ($form->{department}) {
477     ($department) = split /--/, $form->{department};
478     push @options, $locale->text('Department') . " : $department";
479   }
480   if ($form->{donumber}) {
481     push @options, $locale->text('Delivery Order Number') . " : $form->{donumber}";
482   }
483   if ($form->{ordnumber}) {
484     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
485   }
486   if ($form->{transaction_description}) {
487     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
488   }
489   if ($form->{transdatefrom}) {
490     push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
491   }
492   if ($form->{transdateto}) {
493     push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
494   }
495   if ($form->{open}) {
496     push @options, $locale->text('Open');
497   }
498   if ($form->{closed}) {
499     push @options, $locale->text('Closed');
500   }
501   if ($form->{delivered}) {
502     push @options, $locale->text('Delivered');
503   }
504   if ($form->{notdelivered}) {
505     push @options, $locale->text('Not delivered');
506   }
507
508   $report->set_options('top_info_text'        => join("\n", @options),
509                        'raw_top_info_text'    => $form->parse_html_template('do/orders_top'),
510                        'raw_bottom_info_text' => $form->parse_html_template('do/orders_bottom'),
511                        'output_format'        => 'HTML',
512                        'title'                => $form->{title},
513                        'attachment_basename'  => $attachment_basename . strftime('_%Y%m%d', localtime time),
514     );
515   $report->set_options_from_form();
516
517   # add sort and escape callback, this one we use for the add sub
518   $form->{callback} = $href .= "&sort=$form->{sort}";
519
520   # escape callback for href
521   $callback = $form->escape($href);
522
523   my $edit_url       = build_std_url('action=edit', 'type', 'vc');
524   my $edit_order_url = build_std_url('script=oe.pl', 'type=' . ($form->{type} eq 'sales_delivery_order' ? 'sales_order' : 'purchase_order'), 'action=edit');
525
526   my $idx            = 1;
527
528   foreach $dord (@{ $form->{DO} }) {
529     $dord->{open}      = $dord->{closed}    ? $locale->text('No')  : $locale->text('Yes');
530     $dord->{delivered} = $dord->{delivered} ? $locale->text('Yes') : $locale->text('No');
531
532     my $row = { map { $_ => { 'data' => $dord->{$_} } } @columns };
533
534     $row->{ids}  = {
535       'raw_data' =>   $cgi->hidden('-name' => "trans_id_${idx}", '-value' => $dord->{id})
536                     . $cgi->checkbox('-name' => "multi_id_${idx}", '-value' => 1, '-label' => ''),
537       'valign'   => 'center',
538       'align'    => 'center',
539     };
540
541     $row->{donumber}->{link}  = $edit_url       . "&id=" . E($dord->{id})      . "&callback=${callback}";
542     $row->{ordnumber}->{link} = $edit_order_url . "&id=" . E($dord->{oe_id})   . "&callback=${callback}";
543
544     $report->add_data($row);
545
546     $idx++;
547   }
548
549   $report->generate_with_headers();
550
551   $lxdebug->leave_sub();
552 }
553
554 sub save {
555   $lxdebug->enter_sub();
556
557   check_do_access();
558
559   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
560
561   $form->isblank("transdate", $locale->text('Delivery Order Date missing!'));
562
563   $form->{donumber} =~ s/^\s*//g;
564   $form->{donumber} =~ s/\s*$//g;
565
566   $msg = ucfirst $form->{vc};
567   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
568
569   # $locale->text('Customer missing!');
570   # $locale->text('Vendor missing!');
571
572   validate_items();
573
574   # if the name changed get new values
575   if (check_name($form->{vc})) {
576     update();
577     exit;
578   }
579
580   $form->{id} = 0 if $form->{saveasnew};
581
582   DO->save();
583
584   # saving the history
585   if(!exists $form->{addition}) {
586     $form->{snumbers} = qq|donumber_| . $form->{donumber};
587         $form->{addition} = "SAVED";
588         $form->save_history($form->dbconnect(\%myconfig));
589   }
590   # /saving the history
591
592   $form->{simple_save} = 1;
593   if(!$form->{print_and_save}) {
594     set_headings("edit");
595     update();
596     exit;
597   }
598   $lxdebug->leave_sub();
599 }
600
601 sub delete {
602   $lxdebug->enter_sub();
603
604   check_do_access();
605
606   map { delete $form->{$_} } qw(action header login password);
607   my @variables = map { { 'key' => $_, 'value' => $form->{$_} } } grep { '' eq ref $form->{$_} } keys %{ $form };
608
609   $form->{title} = $locale->text('Delete delivery order');
610   $form->header();
611
612   print $form->parse_html_template('do/delete', { 'VARIABLES' => \@variables });
613
614   $lxdebug->leave_sub();
615 }
616
617 sub delete_delivery_order {
618   $lxdebug->enter_sub();
619
620   check_do_access();
621
622   if (DO->delete()) {
623     # saving the history
624     if(!exists $form->{addition}) {
625       $form->{snumbers} = qq|donumber_| . $form->{donumber};
626           $form->{addition} = "DELETED";
627           $form->save_history($form->dbconnect(\%myconfig));
628     }
629     # /saving the history
630
631     $form->info($locale->text('Delivery Order deleted!'));
632     exit();
633   }
634
635   $form->error($locale->text('Cannot delete delivery order!'));
636
637   $lxdebug->leave_sub();
638 }
639
640 sub invoice {
641   $lxdebug->enter_sub();
642
643   check_do_access();
644   $auth->assert($form->{type} eq 'purchase_delivery_order' ? 'vendor_invoice_edit' : 'invoice_edit');
645
646   $form->{convert_from_do_ids} = $form->{id};
647   $form->{deliverydate}        = $form->{transdate};
648   $form->{transdate}           = $form->{invdate} = $form->current_date(\%myconfig);
649   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
650   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
651
652   $form->{rowcount}--;
653
654   delete @{$form}{qw(id closed delivered)};
655
656   if ($form->{type} eq 'purchase_delivery_order') {
657     $form->{title}  = $locale->text('Add Vendor Invoice');
658     $form->{script} = 'ir.pl';
659     $script         = "ir";
660     $buysell        = 'sell';
661
662   } else {
663     $form->{title}  = $locale->text('Add Sales Invoice');
664     $form->{script} = 'is.pl';
665     $script         = "is";
666     $buysell        = 'buy';
667   }
668
669   for $i (1 .. $form->{rowcount}) {
670     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"} } qw(ship qty sellprice listprice basefactor);
671   }
672
673   $form->{type} = "invoice";
674
675   # locale messages
676   $locale = new Locale "$myconfig{countrycode}", "$script";
677
678   require "bin/mozilla/$form->{script}";
679
680   my $currency = $form->{currency};
681   invoice_links();
682
683   $form->{currency}     = $currency;
684   $form->{exchangerate} = "";
685   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, $buysell);
686   $form->{exchangerate} = $form->{forex} if ($form->{forex});
687
688   prepare_invoice();
689
690   # format amounts
691   for $i (1 .. $form->{rowcount}) {
692     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"});
693
694     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
695     $dec           = length $dec;
696     $decimalplaces = ($dec > 2) ? $dec : 2;
697
698     # copy delivery date from reqdate for order -> invoice conversion
699     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
700       unless $form->{"deliverydate_$i"};
701
702     $form->{"sellprice_$i"} =
703       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
704                            $decimalplaces);
705
706     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
707     $dec_qty = length $dec_qty;
708     $form->{"qty_$i"} =
709       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
710
711   }
712
713   display_form();
714
715   $lxdebug->leave_sub();
716 }
717
718 sub invoice_multi {
719   $lxdebug->enter_sub();
720
721   check_do_access();
722   $auth->assert($form->{type} eq 'sales_delivery_order' ? 'invoice_edit' : 'vendor_invoice_edit');
723
724   my @do_ids = map { $form->{"trans_id_$_"} } grep { $form->{"multi_id_$_"} } (1..$form->{rowcount});
725
726   if (!scalar @do_ids) {
727     $form->show_generic_error($locale->text('You have not selected any delivery order.'), 'back_button' => 1);
728   }
729
730   map { delete $form->{$_} } grep { m/^(?:trans|multi)_id_\d+/ } keys %{ $form };
731
732   if (!DO->retrieve('vc' => $form->{vc}, 'ids' => \@do_ids)) {
733     $form->show_generic_error($form->{vc} eq 'customer' ?
734                               $locale->text('You cannot create an invoice for delivery orders for different customers.') :
735                               $locale->text('You cannot create an invoice for delivery orders from different vendors.'),
736                               'back_button' => 1);
737   }
738
739   my $source_type              = $form->{type};
740   $form->{convert_from_do_ids} = join ' ', @do_ids;
741   # bei der auswahl von mehreren Lieferscheinen fuer eine Rechnung, die einfach in donumber_array
742   # zwischenspeichern (DO.pm) und als ' '-separierte Liste wieder zurueckschreiben
743   # Hinweis: delete gibt den wert zurueck und loescht danach das element (nett und einfach)
744   # $shell: perldoc perlunc; /delete EXPR
745   $form->{donumber}            = delete $form->{donumber_array};
746   $form->{deliverydate}        = $form->{transdate};
747   $form->{transdate}           = $form->current_date(\%myconfig);
748   $form->{duedate}             = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
749   $form->{type}                = "invoice";
750   $form->{closed}              = 0;
751   $form->{defaultcurrency}     = $form->get_default_currency(\%myconfig);
752
753   my $buysell;
754   if ($source_type eq 'purchase_delivery_order') {
755     $form->{title}  = $locale->text('Add Vendor Invoice');
756     $form->{script} = 'ir.pl';
757     $script         = "ir";
758     $buysell        = 'sell';
759
760   } else {
761     $form->{title}  = $locale->text('Add Sales Invoice');
762     $form->{script} = 'is.pl';
763     $script         = "is";
764     $buysell        = 'buy';
765   }
766
767   map { delete $form->{$_} } qw(id subject message cc bcc printed emailed queued);
768
769   $form->{rowcount} = 0;
770   foreach my $ref (@{ $form->{form_details} }) {
771     $form->{rowcount}++;
772     $ref->{reqdate} ||= $ref->{dord_transdate}; # copy transdates into each invoice row
773     map { $form->{"${_}_$form->{rowcount}"} = $ref->{$_} } keys %{ $ref };
774     map { $form->{"${_}_$form->{rowcount}"} = $form->format_amount(\%myconfig, $ref->{$_}) } qw(qty sellprice discount lastcost);
775                 $form->{"discount_$form->{rowcount}"}   = $form->{"discount_$form->{rowcount}"}  * 100; #s.a. Bug 1151
776                 # Anm.: Eine Ã„nderung des discounts in der SL/DO.pm->retrieve (select (doi.discount * 100) as discount) ergibt in psql einen
777                 # Wert von 10.0000001490116. Ferner ist der Rabatt in der Rechnung dann bei 1.0 (?). Deswegen lasse ich das hier. jb 10.10.09
778   }
779   delete $form->{form_details};
780
781   $locale = new Locale "$myconfig{countrycode}", "$script";
782
783   require "bin/mozilla/$form->{script}";
784
785   invoice_links();
786   prepare_invoice();
787   display_form();
788
789   $lxdebug->leave_sub();
790 }
791
792 sub save_as_new {
793   $lxdebug->enter_sub();
794
795   check_do_access();
796
797   $form->{saveasnew} = 1;
798   $form->{closed}    = 0;
799   $form->{delivered} = 0;
800   map { delete $form->{$_} } qw(printed emailed queued);
801
802   # Let Lx-Office assign a new order number if the user hasn't changed the
803   # previous one. If it has been changed manually then use it as-is.
804   $form->{donumber} =~ s/^\s*//g;
805   $form->{donumber} =~ s/\s*$//g;
806   if ($form->{saved_donumber} && ($form->{saved_donumber} eq $form->{donumber})) {
807     delete($form->{donumber});
808   }
809
810   save();
811
812   $lxdebug->leave_sub();
813 }
814
815 sub e_mail {
816   $lxdebug->enter_sub();
817
818   check_do_access();
819
820   $form->{print_and_save} = 1;
821
822   $print_post = 1;
823
824   my $saved_form = save_form();
825
826   save();
827
828   restore_form($saved_form, 0, qw(id ordnumber quonumber));
829
830   edit_e_mail();
831
832   $lxdebug->leave_sub();
833 }
834
835 sub calculate_stock_in_out {
836   $lxdebug->enter_sub();
837
838   my $i = shift;
839
840   if (!$form->{"id_${i}"}) {
841     $lxdebug->leave_sub();
842     return '';
843   }
844
845   AM->retrieve_all_units();
846
847   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
848   my $sinfo    = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_${i}"});
849
850   my $sum      = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $sinfo });
851
852   my $content  = $form->format_amount_units('amount'      => $sum * 1,
853                                             'part_unit'   => $form->{"partunit_$i"},
854                                             'amount_unit' => $all_units->{$form->{"partunit_$i"}}->{base_unit},
855                                             'conv_units'  => 'convertible_not_smaller',
856                                             'max_places'  => 2);
857   $content    .= qq| <input type="button" onclick="open_stock_in_out_window('${in_out}', $i);" value="?">|;
858
859   $lxdebug->leave_sub();
860
861   return $content;
862 }
863
864 sub get_basic_bin_wh_info {
865   $lxdebug->enter_sub();
866
867   my $stock_info = shift;
868
869   foreach my $sinfo (@{ $stock_info }) {
870     next unless ($sinfo->{bin_id});
871
872     my $bin_info = WH->get_basic_bin_info('id' => $sinfo->{bin_id});
873     map { $sinfo->{"${_}_description"} = $sinfo->{"${_}description"} = $bin_info->{"${_}_description"} } qw(bin warehouse);
874   }
875
876   $lxdebug->leave_sub();
877 }
878
879 sub stock_in_out_form {
880   $lxdebug->enter_sub();
881
882   if ($form->{in_out} eq 'out') {
883     stock_out_form();
884   } else {
885     stock_in_form();
886   }
887
888   $lxdebug->leave_sub();
889 }
890
891 sub redo_stock_info {
892   $lxdebug->enter_sub();
893
894   my %params    = @_;
895
896   my @non_empty = grep { $_->{qty} } @{ $params{stock_info} };
897
898   if ($params{add_empty_row}) {
899     push @non_empty, {
900       'warehouse_id' => scalar(@non_empty) ? $non_empty[-1]->{warehouse_id} : undef,
901       'bin_id'       => scalar(@non_empty) ? $non_empty[-1]->{bin_id}       : undef,
902     };
903   }
904
905   @{ $params{stock_info} } = @non_empty;
906
907   $lxdebug->leave_sub();
908 }
909
910 sub update_stock_in {
911   $lxdebug->enter_sub();
912
913   my $stock_info = [];
914
915   foreach my $i (1..$form->{rowcount}) {
916     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
917     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber qty unit) };
918   }
919
920   display_stock_in_form($stock_info);
921
922   $lxdebug->leave_sub();
923 }
924
925 sub stock_in_form {
926   $lxdebug->enter_sub();
927
928   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
929
930   display_stock_in_form($stock_info);
931
932   $lxdebug->leave_sub();
933 }
934
935 sub display_stock_in_form {
936   $lxdebug->enter_sub();
937
938   my $stock_info = shift;
939
940   $form->{title} = $locale->text('Stock');
941
942   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
943
944   my $units      = AM->retrieve_units(\%myconfig, $form);
945   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
946
947   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
948                                      'bins'   => 'BINS' });
949
950   redo_stock_info('stock_info' => $stock_info, 'add_empty_row' => !$form->{delivered});
951
952   get_basic_bin_wh_info($stock_info);
953
954   $form->header();
955   print $form->parse_html_template('do/stock_in_form', { 'UNITS'      => $units_data,
956                                                          'STOCK_INFO' => $stock_info,
957                                                          'PART_INFO'  => $part_info, });
958
959   $lxdebug->leave_sub();
960 }
961
962 sub set_stock_in {
963   $lxdebug->enter_sub();
964
965   my $stock_info = [];
966
967   foreach my $i (1..$form->{rowcount}) {
968     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
969
970     next if ($form->{"qty_$i"} <= 0);
971
972     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber qty unit) };
973   }
974
975   $form->{stock} = YAML::Dump($stock_info);
976
977   $form->header();
978   print $form->parse_html_template('do/set_stock_in_out');
979
980   $lxdebug->leave_sub();
981 }
982
983 sub stock_out_form {
984   $lxdebug->enter_sub();
985
986   $form->{title} = $locale->text('Release From Stock');
987
988   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
989
990   my $units      = AM->retrieve_units(\%myconfig, $form);
991   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
992
993   my @contents   = DO->get_item_availability('parts_id' => $form->{parts_id});
994
995   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
996
997   if (!$form->{delivered}) {
998     foreach my $row (@contents) {
999       $row->{available_qty} = $form->format_amount_units('amount'      => $row->{qty} * 1,
1000                                                          'part_unit'   => $part_info->{unit},
1001                                                          'conv_units'  => 'convertible_not_smaller',
1002                                                          'max_places'  => 2);
1003
1004       foreach my $sinfo (@{ $stock_info }) {
1005         next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
1006                  ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1007                  ($row->{chargenumber} ne $sinfo->{chargenumber}));
1008
1009         map { $row->{"stock_$_"} = $sinfo->{$_} } qw(qty unit error);
1010       }
1011     }
1012
1013   } else {
1014     get_basic_bin_wh_info($stock_info);
1015
1016     foreach my $sinfo (@{ $stock_info }) {
1017       map { $sinfo->{"stock_$_"} = $sinfo->{$_} } qw(qty unit);
1018     }
1019   }
1020
1021   $form->header();
1022   print $form->parse_html_template('do/stock_out_form', { 'UNITS'      => $units_data,
1023                                                           'WHCONTENTS' => $form->{delivered} ? $stock_info : \@contents,
1024                                                           'PART_INFO'  => $part_info, });
1025
1026   $lxdebug->leave_sub();
1027 }
1028
1029 sub set_stock_out {
1030   $lxdebug->enter_sub();
1031
1032   my $stock_info = [];
1033
1034   foreach my $i (1 .. $form->{rowcount}) {
1035     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
1036
1037     next if ($form->{"qty_$i"} <= 0);
1038
1039     push @{ $stock_info }, {
1040       'warehouse_id' => $form->{"warehouse_id_$i"},
1041       'bin_id'       => $form->{"bin_id_$i"},
1042       'chargenumber' => $form->{"chargenumber_$i"},
1043       'qty'          => $form->{"qty_$i"},
1044       'unit'         => $form->{"unit_$i"},
1045       'row'          => $i,
1046     };
1047   }
1048
1049   my @errors     = DO->check_stock_availability('requests' => $stock_info,
1050                                                 'parts_id' => $form->{parts_id});
1051
1052   $form->{stock} = YAML::Dump($stock_info);
1053
1054   if (@errors) {
1055     $form->{ERRORS} = [];
1056     map { push @{ $form->{ERRORS} }, $locale->text('Error in row #1: The quantity you entered is bigger than the stocked quantity.', $_->{row}); } @errors;
1057     stock_in_out_form();
1058
1059   } else {
1060     $form->header();
1061     print $form->parse_html_template('do/set_stock_in_out');
1062   }
1063
1064   $lxdebug->leave_sub();
1065 }
1066
1067 sub transfer_in {
1068   $lxdebug->enter_sub();
1069
1070   if (DO->is_marked_as_delivered('id' => $form->{id})) {
1071     $form->show_generic_error($locale->text('The parts for this delivery order have already been transferred in.'), 'back_button' => 1);
1072   }
1073
1074   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_in_${_}"} } (1 .. $form->{rowcount});
1075   my @all_requests;
1076
1077   if (@part_ids) {
1078     my $units         = AM->retrieve_units(\%myconfig, $form);
1079     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1080     my %request_map;
1081
1082     $form->{ERRORS}   = [];
1083
1084     foreach my $i (1 .. $form->{rowcount}) {
1085       next unless ($form->{"id_$i"} && $form->{"stock_in_$i"});
1086
1087       my $row_sum_base_qty = 0;
1088       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1089
1090       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_in_$i"}) }) {
1091         $request->{parts_id}  = $form->{"id_$i"};
1092         $row_sum_base_qty    += $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1093
1094         push @all_requests, $request;
1095       }
1096
1097       next if (0 == $row_sum_base_qty);
1098
1099       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1100
1101       if ($do_base_qty != $row_sum_base_qty) {
1102         push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no stock at all or the full quantity of #2 #3.',
1103                                                  $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1104       }
1105     }
1106
1107     if (@{ $form->{ERRORS} }) {
1108       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been marked as delivered. The warehouse contents have not changed.');
1109
1110       update();
1111       $lxdebug->leave_sub();
1112
1113       exit 0;
1114     }
1115   }
1116
1117   DO->transfer_in_out('direction' => 'in',
1118                       'requests'  => \@all_requests);
1119
1120   $form->{delivered} = 1;
1121
1122   save();
1123
1124   $lxdebug->leave_sub();
1125 }
1126
1127 sub transfer_out {
1128   $lxdebug->enter_sub();
1129
1130   if (DO->is_marked_as_delivered('id' => $form->{id})) {
1131     $form->show_generic_error($locale->text('The parts for this delivery order have already been transferred out.'), 'back_button' => 1);
1132   }
1133
1134   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_out_${_}"} } (1 .. $form->{rowcount});
1135   my @all_requests;
1136
1137   if (@part_ids) {
1138     my $units         = AM->retrieve_units(\%myconfig, $form);
1139     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1140     my %request_map;
1141
1142     $form->{ERRORS}   = [];
1143
1144     foreach my $i (1 .. $form->{rowcount}) {
1145       next unless ($form->{"id_$i"} && $form->{"stock_out_$i"});
1146
1147       my $row_sum_base_qty = 0;
1148       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1149
1150       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_out_$i"}) }) {
1151         $request->{parts_id} = $form->{"id_$i"};
1152         $request->{base_qty} = $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1153
1154         my $map_key          = join '--', ($form->{"id_$i"}, @{$request}{qw(warehouse_id bin_id chargenumber)});
1155
1156         $request_map{$map_key}                 ||= $request;
1157         $request_map{$map_key}->{sum_base_qty} ||= 0;
1158         $request_map{$map_key}->{sum_base_qty}  += $request->{base_qty};
1159         $row_sum_base_qty                       += $request->{base_qty};
1160
1161         push @all_requests, $request;
1162       }
1163
1164       next if (0 == $row_sum_base_qty);
1165
1166       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1167
1168       if ($do_base_qty != $row_sum_base_qty) {
1169         push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no transfer at all or the full quantity of #2 #3.',
1170                                                  $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1171       }
1172     }
1173
1174     if (%request_map) {
1175       my @bin_ids      = map { $_->{bin_id} } values %request_map;
1176       my %bin_info_map = WH->get_basic_bin_info('id' => \@bin_ids);
1177       my @contents     = DO->get_item_availability('parts_id' => \@part_ids);
1178
1179       foreach my $inv (@contents) {
1180         my $map_key = join '--', @{$inv}{qw(parts_id warehouse_id bin_id chargenumber)};
1181
1182         next unless ($request_map{$map_key});
1183
1184         my $request    = $request_map{$map_key};
1185         $request->{ok} = $request->{sum_base_qty} <= $inv->{qty};
1186       }
1187
1188       foreach $request (values %request_map) {
1189         next if ($request->{ok});
1190
1191         my $pinfo = $part_info_map{$request->{parts_id}};
1192         my $binfo = $bin_info_map{$request->{bin_id}};
1193
1194         push @{ $form->{ERRORS} }, $locale->text("There is not enough available of '#1' at warehouse '#2', bin '#3', #4, for the transfer of #5.",
1195                                                  $pinfo->{description}, $binfo->{warehouse_description}, $binfo->{bin_description},
1196                                                  $request->{chargenumber} ? $locale->text('chargenumber #1', $request->{chargenumber}) : $locale->text('no chargenumber'),
1197                                                  $form->format_amount_units('amount'      => $request->{sum_base_qty},
1198                                                                             'part_unit'   => $pinfo->{unit},
1199                                                                             'conv_units'  => 'convertible_not_smaller'));
1200       }
1201     }
1202
1203     if (@{ $form->{ERRORS} }) {
1204       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been marked as delivered. The warehouse contents have not changed.');
1205
1206       update();
1207       $lxdebug->leave_sub();
1208
1209       exit 0;
1210     }
1211   }
1212
1213   DO->transfer_in_out('direction' => 'out',
1214                       'requests'  => \@all_requests);
1215
1216   $form->{delivered} = 1;
1217
1218   save();
1219
1220   $lxdebug->leave_sub();
1221 }
1222
1223 sub mark_closed {
1224   $lxdebug->enter_sub();
1225
1226   DO->close_orders('ids' => [ $form->{id} ]);
1227
1228   $form->{closed} = 1;
1229
1230   update();
1231
1232   $lxdebug->leave_sub();
1233 }
1234
1235
1236 sub yes {
1237   call_sub($form->{yes_nextsub});
1238 }
1239
1240 sub no {
1241   call_sub($form->{no_nextsub});
1242 }
1243
1244 sub update {
1245   call_sub($form->{update_nextsub} || $form->{nextsub} || 'update_delivery_order');
1246 }
1247
1248 sub dispatcher {
1249   foreach my $action (qw(update ship_to print e_mail save transfer_out transfer_in mark_closed save_as_new invoice delete)) {
1250     if ($form->{"action_${action}"}) {
1251       call_sub($action);
1252       return;
1253     }
1254   }
1255
1256   $form->error($locale->text('No action defined.'));
1257 }