ade606bbd09eee2f5b81d3c9ac806e942a618a32
[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}        = ($exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, $buysell));
675   $form->{exchangerate} = $exchangerate 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   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
760   my $sinfo    = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_${i}"});
761
762   my $sum      = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $sinfo });
763
764   my $content  = $form->format_amount_units('amount'      => $sum * 1,
765                                             'part_unit'   => $form->{"partunit_$i"},
766                                             'amount_unit' => $units->{$form->{"partunit_$i"}}->{base_unit},
767                                             'conv_units'  => 'convertible_not_smaller',
768                                             'max_places'  => 2);
769   $content    .= qq| <input type="button" onclick="open_stock_in_out_window('${in_out}', $i);" value="?">|;
770
771   $lxdebug->leave_sub();
772
773   return $content;
774 }
775
776 sub get_basic_bin_wh_info {
777   $lxdebug->enter_sub();
778
779   my $stock_info = shift;
780
781   foreach my $sinfo (@{ $stock_info }) {
782     next unless ($sinfo->{bin_id});
783
784     my $bin_info = WH->get_basic_bin_info('id' => $sinfo->{bin_id});
785     map { $sinfo->{"${_}_description"} = $sinfo->{"${_}description"} = $bin_info->{"${_}_description"} } qw(bin warehouse);
786   }
787
788   $lxdebug->leave_sub();
789 }
790
791 sub stock_in_out_form {
792   $lxdebug->enter_sub();
793
794   if ($form->{in_out} eq 'out') {
795     stock_out_form();
796   } else {
797     stock_in_form();
798   }
799
800   $lxdebug->leave_sub();
801 }
802
803 sub redo_stock_info {
804   $lxdebug->enter_sub();
805
806   my %params    = @_;
807
808   my @non_empty = grep { $_->{qty} } @{ $params{stock_info} };
809
810   if ($params{add_empty_row}) {
811     push @non_empty, {
812       'warehouse_id' => scalar(@non_empty) ? $non_empty[-1]->{warehouse_id} : undef,
813       'bin_id'       => scalar(@non_empty) ? $non_empty[-1]->{bin_id}       : undef,
814     };
815   }
816
817   @{ $params{stock_info} } = @non_empty;
818
819   $lxdebug->leave_sub();
820 }
821
822 sub update_stock_in {
823   $lxdebug->enter_sub();
824
825   my $stock_info = [];
826
827   foreach my $i (1..$form->{rowcount}) {
828     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber qty unit) };
829   }
830   $main::lxdebug->dump(0, "si", $stock_info);
831
832   display_stock_in_form($stock_info);
833
834   $lxdebug->leave_sub();
835 }
836
837 sub stock_in_form {
838   $lxdebug->enter_sub();
839
840   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
841
842   display_stock_in_form($stock_info);
843
844   $lxdebug->leave_sub();
845 }
846
847 sub display_stock_in_form {
848   $lxdebug->enter_sub();
849
850   my $stock_info = shift;
851
852   $form->{title} = $locale->text('Stock');
853
854   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
855
856   my $units      = AM->retrieve_units(\%myconfig, $form, "dimension");
857   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
858
859   my $access     = $auth->check_right($form->{login}, 'all_warehouses') ? undef : $form->{login};
860
861   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
862                                      'bins'   => 'BINS',
863                                      'access' => $access, });
864
865   redo_stock_info('stock_info' => $stock_info, 'add_empty_row' => !$form->{closed});
866
867   get_basic_bin_wh_info($stock_info);
868
869   $form->header();
870   print $form->parse_html_template('do/stock_in_form', { 'UNITS'      => $units_data,
871                                                          'STOCK_INFO' => $stock_info,
872                                                          'PART_INFO'  => $part_info, });
873
874   $lxdebug->leave_sub();
875 }
876
877 sub set_stock_in {
878   $lxdebug->enter_sub();
879
880   my $stock_info = [];
881
882   foreach my $i (1..$form->{rowcount}) {
883     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
884
885     next if ($form->{"qty_$i"} <= 0);
886
887     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber qty unit) };
888   }
889
890   $form->{stock} = YAML::Dump($stock_info);
891
892   $form->header();
893   print $form->parse_html_template('do/set_stock_in_out');
894
895   $lxdebug->leave_sub();
896 }
897
898 sub stock_out_form {
899   $lxdebug->enter_sub();
900
901   $form->{title} = $locale->text('Release From Stock');
902
903   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
904
905   my $units      = AM->retrieve_units(\%myconfig, $form, "dimension");
906   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
907
908   my @contents   = DO->get_item_availability('parts_id' => $form->{parts_id});
909
910   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
911
912   if (!$form->{closed}) {
913     foreach my $row (@contents) {
914       $row->{available_qty} = $form->format_amount_units('amount'      => $row->{qty} * 1,
915                                                          'part_unit'   => $part_info->{unit},
916                                                          'conv_units'  => 'convertible_not_smaller',
917                                                          'max_places'  => 2);
918
919       foreach my $sinfo (@{ $stock_info }) {
920         next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
921                  ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
922                  ($row->{chargenumber} ne $sinfo->{chargenumber}));
923
924         map { $row->{"stock_$_"} = $sinfo->{$_} } qw(qty unit error);
925       }
926     }
927
928   } else {
929     get_basic_bin_wh_info($stock_info);
930
931     foreach my $sinfo (@{ $stock_info }) {
932       map { $sinfo->{"stock_$_"} = $sinfo->{$_} } qw(qty unit);
933     }
934   }
935
936   $form->header();
937   print $form->parse_html_template('do/stock_out_form', { 'UNITS'      => $units_data,
938                                                           'WHCONTENTS' => $form->{closed} ? $stock_info : \@contents,
939                                                           'PART_INFO'  => $part_info, });
940
941   $lxdebug->leave_sub();
942 }
943
944 sub set_stock_out {
945   $lxdebug->enter_sub();
946
947   my $stock_info = [];
948
949   foreach my $i (1 .. $form->{rowcount}) {
950     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
951
952     next if ($form->{"qty_$i"} <= 0);
953
954     push @{ $stock_info }, {
955       'warehouse_id' => $form->{"warehouse_id_$i"},
956       'bin_id'       => $form->{"bin_id_$i"},
957       'chargenumber' => $form->{"chargenumber_$i"},
958       'qty'          => $form->{"qty_$i"},
959       'unit'         => $form->{"unit_$i"},
960       'row'          => $i,
961     };
962   }
963
964   my @errors     = DO->check_stock_availability('requests' => $stock_info,
965                                                 'parts_id' => $form->{parts_id});
966
967   $form->{stock} = YAML::Dump($stock_info);
968
969   if (@errors) {
970     $form->{ERRORS} = [];
971     map { push @{ $form->{ERRORS} }, $locale->text('Error in row #1: The quantity you entered is bigger than the stocked quantity.', $_->{row}); } @errors;
972     stock_in_out_form();
973
974   } else {
975     $form->header();
976     print $form->parse_html_template('do/set_stock_in_out');
977   }
978
979   $lxdebug->leave_sub();
980 }
981
982 sub transfer_in_and_close {
983   $lxdebug->enter_sub();
984
985   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_in_${_}"} } (1 .. $form->{rowcount});
986   my @all_requests;
987
988   if (@part_ids) {
989     my $units         = AM->retrieve_units(\%myconfig, $form, "dimension");
990     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
991     my %request_map;
992
993     $form->{ERRORS}   = [];
994
995     foreach my $i (1 .. $form->{rowcount}) {
996       next unless ($form->{"id_$i"} && $form->{"stock_in_$i"});
997
998       my $row_sum_base_qty = 0;
999       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1000
1001       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_in_$i"}) }) {
1002         $request->{parts_id}  = $form->{"id_$i"};
1003         $row_sum_base_qty    += $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1004
1005         push @all_requests, $request;
1006       }
1007
1008       next if (0 == $row_sum_base_qty);
1009
1010       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1011
1012       if ($do_base_qty != $row_sum_base_qty) {
1013         push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no stock at all or the full quantity of #2 #3.',
1014                                                  $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1015       }
1016     }
1017
1018     if (@{ $form->{ERRORS} }) {
1019       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been closed. The warehouse contents have not changed.');
1020
1021       update();
1022       $lxdebug->leave_sub();
1023
1024       exit 0;
1025     }
1026   }
1027
1028   DO->transfer_in_out('direction' => 'in',
1029                       'requests'  => \@all_requests);
1030
1031   $form->{closed}    = 1;
1032   $form->{delivered} = 1;
1033
1034   save();
1035
1036   $lxdebug->leave_sub();
1037 }
1038
1039 sub transfer_out_and_close {
1040   $lxdebug->enter_sub();
1041
1042   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_out_${_}"} } (1 .. $form->{rowcount});
1043   my @all_requests;
1044
1045   if (@part_ids) {
1046     my $units         = AM->retrieve_units(\%myconfig, $form, "dimension");
1047     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1048     my %request_map;
1049
1050     $form->{ERRORS}   = [];
1051
1052     foreach my $i (1 .. $form->{rowcount}) {
1053       next unless ($form->{"id_$i"} && $form->{"stock_out_$i"});
1054
1055       my $row_sum_base_qty = 0;
1056       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1057
1058       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_out_$i"}) }) {
1059         $request->{parts_id} = $form->{"id_$i"};
1060         $request->{base_qty} = $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1061
1062         my $map_key          = join '--', ($form->{"id_$i"}, @{$request}{qw(warehouse_id bin_id chargenumber)});
1063
1064         $request_map{$map_key}                 ||= $request;
1065         $request_map{$map_key}->{sum_base_qty} ||= 0;
1066         $request_map{$map_key}->{sum_base_qty}  += $request->{base_qty};
1067         $row_sum_base_qty                       += $request->{base_qty};
1068
1069         push @all_requests, $request;
1070       }
1071
1072       next if (0 == $row_sum_base_qty);
1073
1074       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1075
1076       if ($do_base_qty != $row_sum_base_qty) {
1077         push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no transfer at all or the full quantity of #2 #3.',
1078                                                  $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1079       }
1080     }
1081
1082     if (%request_map) {
1083       my @bin_ids      = map { $_->{bin_id} } values %request_map;
1084       my %bin_info_map = WH->get_basic_bin_info('id' => \@bin_ids);
1085       my @contents     = DO->get_item_availability('parts_id' => \@part_ids);
1086
1087       foreach my $inv (@contents) {
1088         my $map_key = join '--', @{$inv}{qw(parts_id warehouse_id bin_id chargenumber)};
1089
1090         next unless ($request_map{$map_key});
1091
1092         my $request    = $request_map{$map_key};
1093         $request->{ok} = $request->{sum_base_qty} <= $inv->{qty};
1094       }
1095
1096       foreach $request (values %request_map) {
1097         next if ($request->{ok});
1098
1099         my $pinfo = $part_info_map{$request->{parts_id}};
1100         my $binfo = $bin_info_map{$request->{bin_id}};
1101
1102         push @{ $form->{ERRORS} }, $locale->text("There is not enough available of '#1' at warehouse '#2', bin '#3', #4, for the transfer of #5.",
1103                                                  $pinfo->{description}, $binfo->{warehouse_description}, $binfo->{bin_description},
1104                                                  $request->{chargenumber} ? $locale->text('chargenumber #1', $request->{chargenumber}) : $locale->text('no chargenumber'),
1105                                                  $form->format_amount_units('amount'      => $request->{sum_base_qty},
1106                                                                             'part_unit'   => $pinfo->{unit},
1107                                                                             'conv_units'  => 'convertible_not_smaller'));
1108       }
1109     }
1110
1111     if (@{ $form->{ERRORS} }) {
1112       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been closed. The warehouse contents have not changed.');
1113
1114       update();
1115       $lxdebug->leave_sub();
1116
1117       exit 0;
1118     }
1119   }
1120
1121   DO->transfer_in_out('direction' => 'out',
1122                       'requests'  => \@all_requests);
1123
1124   $form->{closed}    = 1;
1125   $form->{delivered} = 1;
1126
1127   save();
1128
1129   $lxdebug->leave_sub();
1130 }
1131
1132 sub yes {
1133   call_sub($form->{yes_nextsub});
1134 }
1135
1136 sub no {
1137   call_sub($form->{no_nextsub});
1138 }
1139
1140 sub update {
1141   call_sub($form->{update_nextsub} || $form->{nextsub} || 'update_delivery_order');
1142 }