Kosmetik.
[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               oreqnumber
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     'oreqnumber'              => { 'text' => $locale->text('Order Request Number'), },
449     'name'                    => { 'text' => $form->{vc} eq 'customer' ? $locale->text('Customer') : $locale->text('Vendor'), },
450     'employee'                => { 'text' => $locale->text('Salesperson'), },
451     'shipvia'                 => { 'text' => $locale->text('Ship via'), },
452     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
453     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
454     'open'                    => { 'text' => $locale->text('Open'), },
455     'delivered'               => { 'text' => $locale->text('Delivered'), },
456   );
457
458   foreach my $name (qw(id transdate donumber ordnumber oreqnumber name employee shipvia)) {
459     $column_defs{$name}->{link} = $href . "&sort=$name";
460   }
461
462   $form->{"l_type"} = "Y";
463   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
464   $column_defs{ids}->{visible} = $allow_multiple_orders ? 'HTML' : 0;
465
466   $report->set_columns(%column_defs);
467   $report->set_column_order(@columns);
468
469   $report->set_export_options('orders', @hidden_variables);
470
471   $report->set_sort_indicator($form->{sort}, 1);
472
473   my @options;
474   if ($form->{customer}) {
475     push @options, $locale->text('Customer') . " : $form->{customer}";
476   }
477   if ($form->{vendor}) {
478     push @options, $locale->text('Vendor') . " : $form->{vendor}";
479   }
480   if ($form->{department}) {
481     ($department) = split /--/, $form->{department};
482     push @options, $locale->text('Department') . " : $department";
483   }
484   if ($form->{donumber}) {
485     push @options, $locale->text('Delivery Order Number') . " : $form->{donumber}";
486   }
487   if ($form->{ordnumber}) {
488     push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
489   }
490   if ($form->{transaction_description}) {
491     push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
492   }
493   if ($form->{transdatefrom}) {
494     push @options, $locale->text('From') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
495   }
496   if ($form->{transdateto}) {
497     push @options, $locale->text('Bis') . "&nbsp;" . $locale->date(\%myconfig, $form->{transdateto}, 1);
498   }
499   if ($form->{open}) {
500     push @options, $locale->text('Open');
501   }
502   if ($form->{closed}) {
503     push @options, $locale->text('Closed');
504   }
505   if ($form->{delivered}) {
506     push @options, $locale->text('Delivered');
507   }
508   if ($form->{notdelivered}) {
509     push @options, $locale->text('Not delivered');
510   }
511
512   $report->set_options('top_info_text'       => join("\n", @options),
513                        'output_format'       => 'HTML',
514                        'title'               => $form->{title},
515                        'attachment_basename' => $attachment_basename . strftime('_%Y%m%d', localtime time),
516     );
517   $report->set_options_from_form();
518
519   # add sort and escape callback, this one we use for the add sub
520   $form->{callback} = $href .= "&sort=$form->{sort}";
521
522   # escape callback for href
523   $callback = $form->escape($href);
524
525   my $edit_url       = build_std_url('action=edit', 'type', 'vc');
526   my $edit_order_url = build_std_url('script=oe.pl', 'type=' . ($form->{type} eq 'sales_delivery_order' ? 'sales_order' : 'purchase_order'), 'action=edit');
527   my $edit_oreq_url  = build_std_url('script=pkoreq.pl', 'action=edit');
528
529   foreach $dord (@{ $form->{DO} }) {
530     $dord->{open}      = $dord->{closed}    ? $locale->text('No')  : $locale->text('Yes');
531     $dord->{delivered} = $dord->{delivered} ? $locale->text('Yes') : $locale->text('No');
532
533     my $row = { map { $_ => { 'data' => $dord->{$_} } } @columns };
534
535     $row->{donumber}->{link}   = $edit_url       . "&id=" . E($dord->{id})      . "&callback=${callback}";
536     $row->{ordnumber}->{link}  = $edit_order_url . "&id=" . E($dord->{oe_id})   . "&callback=${callback}";
537     $row->{oreqnumber}->{link} = $edit_oreq_url  . "&id=" . E($dord->{oreq_id}) . "&callback=${callback}";
538
539     $report->add_data($row);
540   }
541
542   $report->generate_with_headers();
543
544   $lxdebug->leave_sub();
545 }
546
547 sub save {
548   $lxdebug->enter_sub();
549
550   check_do_access();
551
552   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
553
554   $form->isblank("transdate", $locale->text('Delivery Order Date missing!'));
555
556   $form->{donumber} =~ s/^\s*//g;
557   $form->{donumber} =~ s/\s*$//g;
558
559   $msg = ucfirst $form->{vc};
560   $form->isblank($form->{vc}, $locale->text($msg . " missing!"));
561
562   # $locale->text('Customer missing!');
563   # $locale->text('Vendor missing!');
564
565   validate_items();
566
567   # if the name changed get new values
568   if (check_name($form->{vc})) {
569     update();
570     exit;
571   }
572
573   $form->{id} = 0 if $form->{saveasnew};
574
575   DO->save();
576
577   # saving the history
578   if(!exists $form->{addition}) {
579     $form->{snumbers} = qq|donumber_| . $form->{donumber};
580         $form->{addition} = "SAVED";
581         $form->save_history($form->dbconnect(\%myconfig));
582   }
583   # /saving the history
584
585   $form->{simple_save} = 1;
586   if(!$form->{print_and_save}) {
587     set_headings("edit");
588     update();
589     exit;
590   }
591   $lxdebug->leave_sub();
592 }
593
594 sub delete {
595   $lxdebug->enter_sub();
596
597   check_do_access();
598
599   map { delete $form->{$_} } qw(action header login password);
600   my @variables = map { { 'key' => $_, 'value' => $form->{$_} } } grep { '' eq ref $form->{$_} } keys %{ $form };
601
602   $form->{title} = $locale->text('Delete delivery order');
603   $form->header();
604
605   print $form->parse_html_template('do/delete', { 'VARIABLES' => \@variables });
606
607   $lxdebug->leave_sub();
608 }
609
610 sub delete_delivery_order {
611   $lxdebug->enter_sub();
612
613   check_do_access();
614
615   if (DO->delete()) {
616     # saving the history
617     if(!exists $form->{addition}) {
618       $form->{snumbers} = qq|donumber_| . $form->{donumber};
619           $form->{addition} = "DELETED";
620           $form->save_history($form->dbconnect(\%myconfig));
621     }
622     # /saving the history
623
624     $form->info($locale->text('Delivery Order deleted!'));
625     exit();
626   }
627
628   $form->error($locale->text('Cannot delete delivery order!'));
629
630   $lxdebug->leave_sub();
631 }
632
633 sub invoice {
634   $lxdebug->enter_sub();
635
636   check_do_access();
637   $auth->assert($form->{type} eq 'purchase_order' || $form->{type} eq 'request_quotation' ? 'vendor_invoice_edit' : 'invoice_edit');
638
639   $form->{deliverydate} = $form->{transdate};
640   $form->{transdate}    = $form->{invdate} = $form->current_date(\%myconfig);
641   $form->{duedate}      = $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
642
643   $form->{id}     = '';
644   $form->{closed} = 0;
645   $form->{rowcount}--;
646
647   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
648
649   if ($form->{type} eq 'purchase_delivery_order') {
650     $form->{title}  = $locale->text('Add Vendor Invoice');
651     $form->{script} = 'ir.pl';
652     $script         = "ir";
653
654   } else {
655     $form->{title}  = $locale->text('Add Sales Invoice');
656     $form->{script} = 'is.pl';
657     $script         = "is";
658     $buysell        = 'buy';
659   }
660
661   for $i (1 .. $form->{rowcount}) {
662     map { $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"}) if $form->{"${_}_${i}"} } qw(ship qty sellprice listprice basefactor);
663   }
664
665   $form->{type} = "invoice";
666
667   # locale messages
668   $locale = new Locale "$myconfig{countrycode}", "$script";
669
670   require "bin/mozilla/$form->{script}";
671
672   my $currency = $form->{currency};
673   invoice_links();
674
675   $form->{currency}     = $currency;
676   $form->{exchangerate} = "";
677   $form->{forex}        = ($exchangerate = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, $buysell));
678   $form->{exchangerate} = $exchangerate if ($form->{forex});
679
680   prepare_invoice();
681
682   # format amounts
683   for $i (1 .. $form->{rowcount}) {
684     $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"});
685
686     ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
687     $dec           = length $dec;
688     $decimalplaces = ($dec > 2) ? $dec : 2;
689
690     # copy delivery date from reqdate for order -> invoice conversion
691     $form->{"deliverydate_$i"} = $form->{"reqdate_$i"}
692       unless $form->{"deliverydate_$i"};
693
694     $form->{"sellprice_$i"} =
695       $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
696                            $decimalplaces);
697
698     (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
699     $dec_qty = length $dec_qty;
700     $form->{"qty_$i"} =
701       $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
702
703   }
704
705   display_form();
706
707   $lxdebug->leave_sub();
708 }
709
710 sub save_as_new {
711   $lxdebug->enter_sub();
712
713   check_do_access();
714
715   $form->{saveasnew} = 1;
716   $form->{closed}    = 0;
717   map { delete $form->{$_} } qw(printed emailed queued);
718
719   # Let Lx-Office assign a new order number if the user hasn't changed the
720   # previous one. If it has been changed manually then use it as-is.
721   $form->{donumber} =~ s/^\s*//g;
722   $form->{donumber} =~ s/\s*$//g;
723   if ($form->{saved_donumber} && ($form->{saved_donumber} eq $form->{donumber})) {
724     delete($form->{donumber});
725   }
726
727   save();
728
729   $lxdebug->leave_sub();
730 }
731
732 sub e_mail {
733   $lxdebug->enter_sub();
734
735   check_do_access();
736
737   $form->{print_and_save} = 1;
738
739   $print_post = 1;
740
741   my $saved_form = save_form();
742
743   save();
744
745   restore_form($saved_form, 0, qw(id ordnumber quonumber));
746
747   edit_e_mail();
748
749   $lxdebug->leave_sub();
750 }
751
752 sub calculate_stock_in_out {
753   $lxdebug->enter_sub();
754
755   my $i = shift;
756
757   if (!$form->{"id_${i}"}) {
758     $lxdebug->leave_sub();
759     return '';
760   }
761
762   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
763   my $sinfo    = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_${i}"});
764
765   my $sum      = AM->sum_with_unit(map { $_->{qty}, $_->{unit} } @{ $sinfo });
766
767   my $content  = $form->format_amount_units('amount'      => $sum * 1,
768                                             'part_unit'   => $form->{"partunit_$i"},
769                                             'amount_unit' => $units->{$form->{"partunit_$i"}}->{base_unit},
770                                             'conv_units'  => 'convertible_not_smaller',
771                                             'max_places'  => 2);
772   $content    .= qq| <input type="button" onclick="open_stock_in_out_window('${in_out}', $i);" value="?">|;
773
774   $lxdebug->leave_sub();
775
776   return $content;
777 }
778
779 sub get_basic_bin_wh_info {
780   $lxdebug->enter_sub();
781
782   my $stock_info = shift;
783
784   foreach my $sinfo (@{ $stock_info }) {
785     next unless ($sinfo->{bin_id});
786
787     my $bin_info = WH->get_basic_bin_info('id' => $sinfo->{bin_id});
788     map { $sinfo->{"${_}_description"} = $sinfo->{"${_}description"} = $bin_info->{"${_}_description"} } qw(bin warehouse);
789   }
790
791   $lxdebug->leave_sub();
792 }
793
794 sub stock_in_out_form {
795   $lxdebug->enter_sub();
796
797   if ($form->{in_out} eq 'out') {
798     stock_out_form();
799   } else {
800     stock_in_form();
801   }
802
803   $lxdebug->leave_sub();
804 }
805
806 sub redo_stock_info {
807   $lxdebug->enter_sub();
808
809   my %params    = @_;
810
811   my @non_empty = grep { $_->{qty} } @{ $params{stock_info} };
812
813   if ($params{add_empty_row}) {
814     push @non_empty, {
815       'warehouse_id' => scalar(@non_empty) ? $non_empty[-1]->{warehouse_id} : undef,
816       'bin_id'       => scalar(@non_empty) ? $non_empty[-1]->{bin_id}       : undef,
817     };
818   }
819
820   @{ $params{stock_info} } = @non_empty;
821
822   $lxdebug->leave_sub();
823 }
824
825 sub update_stock_in {
826   $lxdebug->enter_sub();
827
828   my $stock_info = [];
829
830   foreach my $i (1..$form->{rowcount}) {
831     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber qty unit) };
832   }
833   $main::lxdebug->dump(0, "si", $stock_info);
834
835   display_stock_in_form($stock_info);
836
837   $lxdebug->leave_sub();
838 }
839
840 sub stock_in_form {
841   $lxdebug->enter_sub();
842
843   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
844
845   display_stock_in_form($stock_info);
846
847   $lxdebug->leave_sub();
848 }
849
850 sub display_stock_in_form {
851   $lxdebug->enter_sub();
852
853   my $stock_info = shift;
854
855   $form->{title} = $locale->text('Stock');
856
857   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
858
859   my $units      = AM->retrieve_units(\%myconfig, $form, "dimension");
860   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
861
862   my $access     = $auth->check_right($form->{login}, 'all_warehouses') ? undef : $form->{login};
863
864   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
865                                      'bins'   => 'BINS',
866                                      'access' => $access, });
867
868   redo_stock_info('stock_info' => $stock_info, 'add_empty_row' => !$form->{closed});
869
870   get_basic_bin_wh_info($stock_info);
871
872   $form->header();
873   print $form->parse_html_template('do/stock_in_form', { 'UNITS'      => $units_data,
874                                                          'STOCK_INFO' => $stock_info,
875                                                          'PART_INFO'  => $part_info, });
876
877   $lxdebug->leave_sub();
878 }
879
880 sub set_stock_in {
881   $lxdebug->enter_sub();
882
883   my $stock_info = [];
884
885   foreach my $i (1..$form->{rowcount}) {
886     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
887
888     next if ($form->{"qty_$i"} <= 0);
889
890     push @{ $stock_info }, { map { $_ => $form->{"${_}_${i}"} } qw(warehouse_id bin_id chargenumber qty unit) };
891   }
892
893   $form->{stock} = YAML::Dump($stock_info);
894
895   $form->header();
896   print $form->parse_html_template('do/set_stock_in_out');
897
898   $lxdebug->leave_sub();
899 }
900
901 sub stock_out_form {
902   $lxdebug->enter_sub();
903
904   $form->{title} = $locale->text('Release From Stock');
905
906   my $part_info  = IC->get_basic_part_info('id' => $form->{parts_id});
907
908   my $units      = AM->retrieve_units(\%myconfig, $form, "dimension");
909   my $units_data = AM->unit_select_data($units, undef, undef, $part_info->{unit});
910
911   my @contents   = DO->get_item_availability('parts_id' => $form->{parts_id});
912
913   my $stock_info = DO->unpack_stock_information('packed' => $form->{stock});
914
915   if (!$form->{closed}) {
916     foreach my $row (@contents) {
917       $row->{available_qty} = $form->format_amount_units('amount'      => $row->{qty} * 1,
918                                                          'part_unit'   => $part_info->{unit},
919                                                          'conv_units'  => 'convertible_not_smaller',
920                                                          'max_places'  => 2);
921
922       foreach my $sinfo (@{ $stock_info }) {
923         next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
924                  ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
925                  ($row->{chargenumber} ne $sinfo->{chargenumber}));
926
927         map { $row->{"stock_$_"} = $sinfo->{$_} } qw(qty unit error);
928       }
929     }
930
931   } else {
932     get_basic_bin_wh_info($stock_info);
933
934     foreach my $sinfo (@{ $stock_info }) {
935       map { $sinfo->{"stock_$_"} = $sinfo->{$_} } qw(qty unit);
936     }
937   }
938
939   $form->header();
940   print $form->parse_html_template('do/stock_out_form', { 'UNITS'      => $units_data,
941                                                           'WHCONTENTS' => $form->{closed} ? $stock_info : \@contents,
942                                                           'PART_INFO'  => $part_info, });
943
944   $lxdebug->leave_sub();
945 }
946
947 sub set_stock_out {
948   $lxdebug->enter_sub();
949
950   my $stock_info = [];
951
952   foreach my $i (1 .. $form->{rowcount}) {
953     $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
954
955     next if ($form->{"qty_$i"} <= 0);
956
957     push @{ $stock_info }, {
958       'warehouse_id' => $form->{"warehouse_id_$i"},
959       'bin_id'       => $form->{"bin_id_$i"},
960       'chargenumber' => $form->{"chargenumber_$i"},
961       'qty'          => $form->{"qty_$i"},
962       'unit'         => $form->{"unit_$i"},
963       'row'          => $i,
964     };
965   }
966
967   my @errors     = DO->check_stock_availability('requests' => $stock_info,
968                                                 'parts_id' => $form->{parts_id});
969
970   $form->{stock} = YAML::Dump($stock_info);
971
972   if (@errors) {
973     $form->{ERRORS} = [];
974     map { push @{ $form->{ERRORS} }, $locale->text('Error in row #1: The quantity you entered is bigger than the stocked quantity.', $_->{row}); } @errors;
975     stock_in_out_form();
976
977   } else {
978     $form->header();
979     print $form->parse_html_template('do/set_stock_in_out');
980   }
981
982   $lxdebug->leave_sub();
983 }
984
985 sub transfer_in_and_close {
986   $lxdebug->enter_sub();
987
988   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_in_${_}"} } (1 .. $form->{rowcount});
989   my @all_requests;
990
991   if (@part_ids) {
992     my $units         = AM->retrieve_units(\%myconfig, $form, "dimension");
993     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
994     my %request_map;
995
996     $form->{ERRORS}   = [];
997
998     foreach my $i (1 .. $form->{rowcount}) {
999       next unless ($form->{"id_$i"} && $form->{"stock_in_$i"});
1000
1001       my $row_sum_base_qty = 0;
1002       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1003
1004       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_in_$i"}) }) {
1005         $request->{parts_id}  = $form->{"id_$i"};
1006         $row_sum_base_qty    += $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1007
1008         push @all_requests, $request;
1009       }
1010
1011       next if (0 == $row_sum_base_qty);
1012
1013       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1014
1015       if ($do_base_qty != $row_sum_base_qty) {
1016         push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no stock at all or the full quantity of #2 #3.',
1017                                                  $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1018       }
1019     }
1020
1021     if (@{ $form->{ERRORS} }) {
1022       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been closed. The warehouse contents have not changed.');
1023
1024       update();
1025       $lxdebug->leave_sub();
1026
1027       exit 0;
1028     }
1029   }
1030
1031   DO->transfer_in_out('direction' => 'in',
1032                       'requests'  => \@all_requests);
1033
1034   $form->{closed}    = 1;
1035   $form->{delivered} = 1;
1036
1037   save();
1038
1039   $lxdebug->leave_sub();
1040 }
1041
1042 sub transfer_out_and_close {
1043   $lxdebug->enter_sub();
1044
1045   my @part_ids = map { $form->{"id_${_}"} } grep { $form->{"id_${_}"} && $form->{"stock_out_${_}"} } (1 .. $form->{rowcount});
1046   my @all_requests;
1047
1048   if (@part_ids) {
1049     my $units         = AM->retrieve_units(\%myconfig, $form, "dimension");
1050     my %part_info_map = IC->get_basic_part_info('id' => \@part_ids);
1051     my %request_map;
1052
1053     $form->{ERRORS}   = [];
1054
1055     foreach my $i (1 .. $form->{rowcount}) {
1056       next unless ($form->{"id_$i"} && $form->{"stock_out_$i"});
1057
1058       my $row_sum_base_qty = 0;
1059       my $base_unit_factor = $units->{ $part_info_map{$form->{"id_$i"}}->{unit} }->{factor} || 1;
1060
1061       foreach my $request (@{ DO->unpack_stock_information('packed' => $form->{"stock_out_$i"}) }) {
1062         $request->{parts_id} = $form->{"id_$i"};
1063         $request->{base_qty} = $request->{qty} * $units->{$request->{unit}}->{factor} / $base_unit_factor;
1064
1065         my $map_key          = join '--', ($form->{"id_$i"}, @{$request}{qw(warehouse_id bin_id chargenumber)});
1066
1067         $request_map{$map_key}                 ||= $request;
1068         $request_map{$map_key}->{sum_base_qty} ||= 0;
1069         $request_map{$map_key}->{sum_base_qty}  += $request->{base_qty};
1070         $row_sum_base_qty                       += $request->{base_qty};
1071
1072         push @all_requests, $request;
1073       }
1074
1075       next if (0 == $row_sum_base_qty);
1076
1077       my $do_base_qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"}) * $units->{$form->{"unit_$i"}}->{factor} / $base_unit_factor;
1078
1079       if ($do_base_qty != $row_sum_base_qty) {
1080         push @{ $form->{ERRORS} }, $locale->text('Error in position #1: You must either assign no transfer at all or the full quantity of #2 #3.',
1081                                                  $i, $form->{"qty_$i"}, $form->{"unit_$i"});
1082       }
1083     }
1084
1085     if (%request_map) {
1086       my @bin_ids      = map { $_->{bin_id} } values %request_map;
1087       my %bin_info_map = WH->get_basic_bin_info('id' => \@bin_ids);
1088       my @contents     = DO->get_item_availability('parts_id' => \@part_ids);
1089
1090       foreach my $inv (@contents) {
1091         my $map_key = join '--', @{$inv}{qw(parts_id warehouse_id bin_id chargenumber)};
1092
1093         next unless ($request_map{$map_key});
1094
1095         my $request    = $request_map{$map_key};
1096         $request->{ok} = $request->{sum_base_qty} <= $inv->{qty};
1097       }
1098
1099       foreach $request (values %request_map) {
1100         next if ($request->{ok});
1101
1102         my $pinfo = $part_info_map{$request->{parts_id}};
1103         my $binfo = $bin_info_map{$request->{bin_id}};
1104
1105         push @{ $form->{ERRORS} }, $locale->text("There is not enough available of '#1' at warehouse '#2', bin '#3', #4, for the transfer of #5.",
1106                                                  $pinfo->{description}, $binfo->{warehouse_description}, $binfo->{bin_description},
1107                                                  $request->{chargenumber} ? $locale->text('chargenumber #1', $request->{chargenumber}) : $locale->text('no chargenumber'),
1108                                                  $form->format_amount_units('amount'      => $request->{sum_base_qty},
1109                                                                             'part_unit'   => $pinfo->{unit},
1110                                                                             'conv_units'  => 'convertible_not_smaller'));
1111       }
1112     }
1113
1114     if (@{ $form->{ERRORS} }) {
1115       push @{ $form->{ERRORS} }, $locale->text('The delivery order has not been closed. The warehouse contents have not changed.');
1116
1117       update();
1118       $lxdebug->leave_sub();
1119
1120       exit 0;
1121     }
1122   }
1123
1124   DO->transfer_in_out('direction' => 'out',
1125                       'requests'  => \@all_requests);
1126
1127   $form->{closed}    = 1;
1128   $form->{delivered} = 1;
1129
1130   save();
1131
1132   $lxdebug->leave_sub();
1133 }
1134
1135 sub yes {
1136   call_sub($form->{yes_nextsub});
1137 }
1138
1139 sub no {
1140   call_sub($form->{no_nextsub});
1141 }
1142
1143 sub update {
1144   call_sub($form->{update_nextsub} || $form->{nextsub} || 'update_delivery_order');
1145 }