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