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