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