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