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