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