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