Merge branch 'master' of ssh://git-jbueren@lx-office.linet-services.de/~/lx-office-erp
[kivitendo-erp.git] / bin / mozilla / wh.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 # SQL-Ledger, Accounting
8 # Copyright (c) 1998-2002
9 #
10 #  Author: Dieter Simader
11 #   Email: dsimader@sql-ledger.org
12 #     Web: http://www.sql-ledger.org
13 #
14 #
15 # This program is free software; you can redistribute it and/or modify
16 # it under the terms of the GNU General Public License as published by
17 # the Free Software Foundation; either version 2 of the License, or
18 # (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #
28 #######################################################################
29 #
30 # warehouse and packinglist
31 #
32 #######################################################################
33
34 use List::Util qw(min max first);
35 use POSIX qw(strftime);
36
37 use SL::Form;
38 use SL::User;
39
40 use SL::AM;
41 use SL::CT;
42 use SL::IC;
43 use SL::WH;
44 use SL::OE;
45 use SL::ReportGenerator;
46
47 use Data::Dumper;
48
49 require "bin/mozilla/common.pl";
50 require "bin/mozilla/reportgenerator.pl";
51
52 use strict;
53
54 # parserhappy(R):
55
56 # contents of the "transfer_type" table:
57 #  $locale->text('back')
58 #  $locale->text('correction')
59 #  $locale->text('disposed')
60 #  $locale->text('found')
61 #  $locale->text('missing')
62 #  $locale->text('stock')
63 #  $locale->text('shipped')
64 #  $locale->text('transfer')
65 #  $locale->text('used')
66 #  $locale->text('return_material')
67 #  $locale->text('release_material')
68
69 # --------------------------------------------------------------------
70 # Transfer
71 # --------------------------------------------------------------------
72
73 sub transfer_warehouse_selection {
74   $main::lxdebug->enter_sub();
75
76   $main::auth->assert('warehouse_management');
77
78   my $form     = $main::form;
79   my %myconfig = %main::myconfig;
80   my $locale   = $main::locale;
81
82   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
83                                      'bins'   => 'BINS', });
84
85   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
86
87   my $units      = AM->retrieve_units(\%myconfig, $form);
88   # der zweite Parameter von unit_select_data gibt den default-Namen (selected) vor
89   $form->{UNITS} = AM->unit_select_data($units, $form->{partunit}, 0, $form->{partunit});
90
91   if (scalar @{ $form->{WAREHOUSES} }) {
92     $form->{warehouse_id} ||= $form->{WAREHOUSES}->[0]->{id};
93     $form->{bin_id}       ||= $form->{WAREHOUSES}->[0]->{BINS}->[0]->{id};
94   }
95
96   my $content;
97
98   $form->{jsscript} = 1;
99
100   if ($form->{trans_type} eq 'removal') {
101     $form->{nextsub} = "removal_parts_selection";
102     $form->{title}   = $locale->text('Removal from Warehouse');
103     $content         = $form->parse_html_template('wh/warehouse_selection');
104
105   } elsif ($form->{trans_type} eq 'stock') {
106     $form->{title} = $locale->text('Stock');
107     $content       = $form->parse_html_template('wh/warehouse_selection_stock');
108
109   } elsif (!$form->{trans_type} || ($form->{trans_type} eq 'transfer')) {
110     $form->{nextsub} = "transfer_parts_selection";
111     $form->{title}   = $locale->text('Transfer');
112     $content         = $form->parse_html_template('wh/warehouse_selection');
113
114   } elsif ($form->{trans_type} eq 'assembly') {
115     $form->{title} = $locale->text('Produce Assembly');
116     $content       = $form->parse_html_template('wh/warehouse_selection_assembly');
117   }
118
119   $form->header();
120   print $content;
121
122   $main::lxdebug->leave_sub();
123 }
124
125 sub transfer_parts_selection {
126   $main::lxdebug->enter_sub();
127
128   $main::auth->assert('warehouse_management');
129
130   my $form     = $main::form;
131   my %myconfig = %main::myconfig;
132   my $locale   = $main::locale;
133
134   transfer_or_removal_prepare_contents('direction' => 'transfer');
135
136   $form->{title} = $locale->text('Transfer');
137   $form->header();
138   print $form->parse_html_template("wh/transfer_parts_selection");
139
140   $main::lxdebug->leave_sub();
141 }
142
143 sub transfer_or_removal_prepare_contents {
144   $main::lxdebug->enter_sub();
145
146   $main::auth->assert('warehouse_management');
147
148   my %args = @_;
149
150   my $form     = $main::form;
151   my %myconfig = %main::myconfig;
152   my $locale   = $main::locale;
153
154   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
155                                      'bins'   => 'BINS', });
156
157   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
158   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
159
160   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
161
162   $form->{initial_warehouse_idx} = $warehouse_idx;
163   $form->{warehouse_description} = $warehouse->{description};
164   $warehouse->{selected}         = 1;
165
166   $form->show_generic_error($locale->text("The source warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
167
168   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber bestbefore partunit ean);
169
170   $form->{sort} = 'bindescription';
171   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id},
172                                            "bin_id"       => $form->{bin_id},
173                                            "chargenumber" => $form->{chargenumber},
174                                            "bestbefore"   => $form->{bestbefore},
175                                            "partnumber"   => $form->{partnumber},
176                                            "ean"          => $form->{ean},
177                                            "description"  => $form->{description});
178
179   $form->show_generic_error($locale->text("The selected warehouse is empty.")) if (0 == scalar(@contents));
180
181   my $all_units = AM->retrieve_units(\%myconfig, $form);
182
183   foreach (@contents) {
184     $_->{qty} = $form->format_amount_units('amount'     => $_->{qty},
185                                            'part_unit'  => $_->{partunit},
186                                            'conv_units' => 'convertible');
187     my $this_unit = $_->{partunit};
188
189     if ($all_units->{$_->{partunit}} && ($all_units->{g}->{base_unit} eq $all_units->{$_->{partunit}}->{base_unit})) {
190       $this_unit = "kg";
191     }
192
193     $_->{UNITS} = AM->unit_select_data($all_units, $this_unit, 0, $_->{partunit});
194   }
195
196   my $transfer_types = WH->retrieve_transfer_types($args{direction});
197   map { $_->{description} = $locale->text($_->{description}) } @{ $transfer_types };
198
199   $form->{CONTENTS}       = \@contents;
200   $form->{TRANSFER_TYPES} = $transfer_types;
201
202   $main::lxdebug->leave_sub();
203 }
204
205
206 sub transfer_parts {
207   $main::lxdebug->enter_sub();
208
209   $main::auth->assert('warehouse_management');
210
211   my $form     = $main::form;
212   my %myconfig = %main::myconfig;
213   my $locale   = $main::locale;
214
215   $form->get_lists('warehouses' => { 'key' => 'WAREHOUSES', 'bins' => 'BINS' });
216
217   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
218   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
219
220   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
221
222   $form->show_generic_error($locale->text("The source warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
223
224   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber bestbefore partunit);
225
226   $form->{sort} = 'bindescription';
227   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id});
228   my $all_units = AM->retrieve_units(\%myconfig, $form);
229
230   my @transfers;
231
232   foreach my $row (1 .. $form->{rowcount}) {
233     $form->{"qty_$row"} =~ s/^\s*//;
234     $form->{"qty_$row"} =~ s/\s*$//;
235     next if (!$form->{"qty_$row"});
236
237     my $bin_idx = get_bin_idx($warehouse_idx, $form->{"src_bin_id_$row"});
238     $form->show_generic_error($locale->text("The selected bin does not exist.")) if (-1 == $bin_idx);
239     my $bin     = $warehouse->{BINS}->[$bin_idx];
240
241     my $orig_qty = $form->{"qty_$row"} . " " . $form->{"unit_$row"};
242
243     my $transfer = {
244       'src_warehouse_id' => $form->{warehouse_id},
245       'transfer_type_id' => $form->{transfer_type_id},
246     };
247
248     map { $transfer->{$_} = $form->{"${_}_${row}"} } qw(src_bin_id chargenumber bestbefore parts_id qty dst_warehouse_id dst_bin_id);
249
250     my $entry;
251
252     foreach (@contents) {
253       if (($_->{binid} == $transfer->{src_bin_id}) && ($_->{parts_id} == $transfer->{parts_id}) && ($_->{chargenumber} eq $transfer->{chargenumber}) && $_->{bestbefore} eq $transfer->{bestbefore}) {
254         $entry = $_;
255         last;
256       }
257     }
258
259     if (!$entry) {
260       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
261                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
262     }
263
264     $transfer->{qty}  = $form->parse_amount(\%myconfig, $transfer->{qty}) * $all_units->{$form->{"unit_$row"}}->{factor};
265     $transfer->{qty} /= $all_units->{$entry->{partunit}}->{factor} || 1;
266
267     if (($entry->{qty} < $transfer->{qty}) || (0 >= $transfer->{qty})) {
268       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
269                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
270     }
271
272     $transfer->{comment} = $form->{comment};
273
274     push @transfers, $transfer;
275
276     $entry->{qty} -= $transfer->{qty};
277   }
278
279   if (!scalar @transfers) {
280     $form->show_generic_information($locale->text('Nothing has been selected for transfer.'));
281     ::end_of_request();
282   }
283
284   WH->transfer(@transfers);
285
286   $form->{trans_type}    = 'transfer';
287   $form->{saved_message} = $locale->text('The parts have been transferred.');
288
289   transfer_warehouse_selection();
290
291   $main::lxdebug->leave_sub();
292 }
293
294 # --------------------------------------------------------------------
295 # Transfer: stock
296 # --------------------------------------------------------------------
297
298 sub transfer_stock_update_part {
299   $main::lxdebug->enter_sub();
300
301   my $form     = $main::form;
302   my %myconfig = %main::myconfig;
303   my $locale   = $main::locale;
304
305   $form->{trans_type} = 'stock';
306   $form->{qty}        = $form->parse_amount(\%myconfig, $form->{qty});
307
308   if (!$form->{partnumber} && !$form->{description} && !$form->{ean}) {
309     delete @{$form}{qw(parts_id partunit ean)};
310     transfer_warehouse_selection();
311
312   } elsif (($form->{partnumber} && ($form->{partnumber} ne $form->{old_partnumber})) || $form->{description} || $form->{ean}) {
313
314 #    $form->{no_services}   = 1; # services may now be transfered. fix for Bug 1383.
315     $form->{no_assemblies} = 0; # assemblies duerfen eingelagert werden (z.B. bei retouren)
316
317     my $parts = Common->retrieve_parts(\%myconfig, $form, 'description', 1);
318
319     if (!scalar @{ $parts }) {
320       new_item(action => "transfer_stock_update_part");
321     } elsif (scalar @{ $parts } == 1) {
322       @{$form}{qw(parts_id partnumber description ean)} = @{$parts->[0]}{qw(id partnumber description ean)};
323       transfer_stock_get_partunit();
324       transfer_warehouse_selection();
325
326     } else {
327       select_part('transfer_stock_part_selected', @{ $parts });
328     }
329
330   } else {
331     transfer_stock_get_partunit();
332     transfer_warehouse_selection();
333   }
334
335   $main::lxdebug->leave_sub();
336 }
337
338 # --------------------------------------------------------------------
339 # Transfer: assemblies
340 # Dies ist die Auswahlmaske für ein assembly.
341 # Die ist einfach von transfer_assembly_update_part kopiert und nur um den trans_type (assembly) korrigiert worden
342 # Es wäre schön, hier nochmal check_assembly_max_create auf, um die max. Fertigungszahl herauszufinden.
343 # Ich lass das mal als auskommentierte Idee bestehen jb 18.3.09
344 # --------------------------------------------------------------------
345
346 sub transfer_assembly_update_part {
347   $main::lxdebug->enter_sub();
348
349   my $form     = $main::form;
350   my %myconfig = %main::myconfig;
351   my $locale   = $main::locale;
352
353   $form->{trans_type} = 'assembly';
354   $form->{qty}        = $form->parse_amount(\%myconfig, $form->{qty});
355
356   if (!$form->{partnumber} && !$form->{description}) {
357     delete @{$form}{qw(parts_id partunit)};
358     transfer_warehouse_selection();
359
360   } elsif (($form->{partnumber} && ($form->{partnumber} ne $form->{old_partnumber})) || $form->{description}) {
361     $form->{assemblies} = 1;
362     $form->{no_assemblies} = 0;
363     my $parts = Common->retrieve_parts(\%myconfig, $form, 'description', 1);
364     if (scalar @{ $parts } == 1) {
365       @{$form}{qw(parts_id partnumber description)} = @{$parts->[0]}{qw(id partnumber description)};
366       transfer_stock_get_partunit();
367       transfer_warehouse_selection();
368     } else {
369       select_part('transfer_stock_part_selected', @{ $parts });
370     }
371
372   } else {
373     transfer_stock_get_partunit();
374     transfer_warehouse_selection();
375   }
376
377 # hier die oben benannte idee
378 #    my $maxcreate = Common->check_assembly_max_create(assembly_id => $form->{parts_id}, dbh => $my_dbh);
379   $main::lxdebug->leave_sub();
380 }
381
382 sub transfer_stock_part_selected {
383   $main::lxdebug->enter_sub();
384
385   my $part = shift;
386
387   my $form     = $main::form;
388
389   @{$form}{qw(parts_id partnumber description ean)} = @{$part}{qw(id partnumber description ean)};
390
391   transfer_stock_get_partunit();
392   transfer_warehouse_selection();
393
394   $main::lxdebug->leave_sub();
395 }
396
397 sub transfer_stock_get_partunit {
398   $main::lxdebug->enter_sub();
399
400   my $form     = $main::form;
401
402   if ($form->{parts_id}) {
403     my $part_info     = IC->get_basic_part_info('id' => $form->{parts_id});
404     $form->{partunit} = $part_info->{unit};
405   }
406
407   $main::lxdebug->leave_sub();
408 }
409
410 # vorüberlegung jb 22.2.2009
411 # wir benötigen für diese funktion, die anzahl die vom erzeugnis hergestellt werden soll. vielleicht direkt per js fehleingaben verhindern?
412 # ferner dann nochmal mit check_asssembly_max_create gegenprüfen und dann transaktionssicher wegbuchen.
413 # wir brauchen eine hilfsfunktion, die nee. brauchen wir nicht. der algorithmus läuft genau wie bei check max_create, nur dass hier auch eine lagerbewegung (verbraucht) stattfindet
414 # Manko ist derzeit noch, dass unterschiedliche Lagerplätze, bzw. das Quelllager an sich nicht ausgewählt werden können.
415 # Laut Absprache in KW11 09 Ã¼bernimmt mb hier den rest im April ... jb 18.3.09
416
417 sub create_assembly {
418   $main::lxdebug->enter_sub();
419
420   my $form     = $main::form;
421   my %myconfig = %main::myconfig;
422   my $locale   = $main::locale;
423
424   $form->{qty} = $form->parse_amount(\%myconfig, $form->{qty});
425   if ($form->{qty} <= 0) {
426     $form->show_generic_error($locale->text('Invalid quantity.'), 'back_button' => 1);
427   }
428   # TODO Es wäre schön, hier schon die maximale Anzahl der zu fertigenden Erzeugnisse zu haben
429   #else { if ($form->{qty} > $maxcreate) { #s.o.
430   #     $form->show_generic_error($locale->text('Can not create that quantity with current stock'), 'back_button' => 1);
431   #     $form->show_generic_error('Maximale Stückzahl' . $maxcreate , 'back_button' => 1);
432   #   }
433   #  }
434
435   if (!$form->{warehouse_id} || !$form->{bin_id}) {
436     $form->error($locale->text('The warehouse or the bin is missing.'));
437   }
438
439   if (!$main::show_best_before) {
440       $form->{bestbefore} = '';
441   }
442
443   # WIESO war das nicht vorher schon ein %HASH?? ein hash ist ein hash! das hat mich mehr als eine Stunde gekostet herauszufinden. grr. jb 3.3.2009
444   # Anm. jb 18.3. vielleicht auch nur meine unwissenheit in perl-datenstrukturen
445   my %TRANSFER = (
446     'transfer_type'    => 'assembly',
447     'login'            => $form->{login},
448     'dst_warehouse_id' => $form->{warehouse_id},
449     'dst_bin_id'       => $form->{bin_id},
450     'chargenumber'     => $form->{chargenumber},
451     'bestbefore'       => $form->{bestbefore},
452     'assembly_id'      => $form->{parts_id},
453     'qty'              => $form->{qty},
454     'unit'             => $form->{unit},
455     'comment'          => $form->{comment}
456   );
457
458   my $ret = WH->transfer_assembly (%TRANSFER);
459   # Frage: Ich pack in den return-wert auch gleich die Fehlermeldung. Irgendwelche Nummern als Fehlerkonstanten definieren find ich auch nicht besonders schick...
460   # Ideen? jb 18.3.09
461   if ($ret ne "1"){
462     # Die locale-Funktion kann keine Double-Quotes escapen, deswegen hier erstmal so (ein wahrscheinlich immerwährender Hotfix) s.a. Frage davor jb 25.4.09
463     $form->show_generic_error($ret, 'back_button' => 1);
464   }
465
466   delete @{$form}{qw(parts_id partnumber description qty unit chargenumber bestbefore comment)};
467
468   $form->{saved_message} = $locale->text('The assembly has been created.');
469   $form->{trans_type}    = 'assembly';
470
471   transfer_warehouse_selection();
472
473   $main::lxdebug->leave_sub();
474 }
475
476 sub transfer_stock {
477   $main::lxdebug->enter_sub();
478
479   my $form     = $main::form;
480   my %myconfig = %main::myconfig;
481   my $locale   = $main::locale;
482
483   $form->{qty} = $form->parse_amount(\%myconfig, $form->{qty});
484
485   if ($form->{qty} <= 0) {
486     $form->show_generic_error($locale->text('Invalid quantity.'), 'back_button' => 1);
487   }
488
489   if (!$form->{warehouse_id} || !$form->{bin_id}) {
490     $form->error($locale->text('The warehouse or the bin is missing.'));
491   }
492
493   my $transfer = {
494     'transfer_type'    => 'stock',
495     'dst_warehouse_id' => $form->{warehouse_id},
496     'dst_bin_id'       => $form->{bin_id},
497     'chargenumber'     => $form->{chargenumber},
498     'bestbefore'       => $form->{bestbefore},
499     'parts_id'         => $form->{parts_id},
500     'qty'              => $form->{qty},
501     'unit'             => $form->{unit},
502     'comment'          => $form->{comment},
503   };
504
505   WH->transfer($transfer);
506
507   delete @{$form}{qw(parts_id partnumber description qty unit chargenumber bestbefore comment ean)};
508
509   $form->{saved_message} = $locale->text('The parts have been stocked.');
510   $form->{trans_type}    = 'stock';
511
512   transfer_warehouse_selection();
513
514   $main::lxdebug->leave_sub();
515 }
516
517 # --------------------------------------------------------------------
518 # Transfer: removal
519 # --------------------------------------------------------------------
520
521 sub removal_parts_selection {
522   $main::lxdebug->enter_sub();
523
524   $main::auth->assert('warehouse_management');
525
526   my $form     = $main::form;
527   my %myconfig = %main::myconfig;
528   my $locale   = $main::locale;
529
530   transfer_or_removal_prepare_contents('direction' => 'out');
531
532   $form->{title} = $locale->text('Removal');
533   $form->header();
534   print $form->parse_html_template("wh/removal_parts_selection");
535
536   $main::lxdebug->leave_sub();
537 }
538
539 sub remove_parts {
540   $main::lxdebug->enter_sub();
541
542   $main::auth->assert('warehouse_management');
543
544   my $form     = $main::form;
545   my %myconfig = %main::myconfig;
546   my $locale   = $main::locale;
547
548   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
549                                      'bins'   => 'BINS', });
550
551   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
552   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
553
554   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
555
556   $form->show_generic_error($locale->text("The warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
557
558   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber bestbefore partunit);
559
560   $form->{sort} = 'bindescription';
561   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id});
562   my $all_units = AM->retrieve_units(\%myconfig, $form);
563
564   my @transfers;
565
566   foreach my $row (1 .. $form->{rowcount}) {
567     $form->{"qty_$row"} =~ s/^\s*//;
568     $form->{"qty_$row"} =~ s/\s*$//;
569     next if (!$form->{"qty_$row"});
570
571     my $bin_idx = get_bin_idx($warehouse_idx, $form->{"src_bin_id_$row"});
572     $form->show_generic_error($locale->text("The selected bin does not exist.")) if (-1 == $bin_idx);
573     my $bin     = $warehouse->{BINS}->[$bin_idx];
574
575     my $orig_qty = $form->{"qty_$row"} . " " . $form->{"unit_$row"};
576
577     my $transfer = {
578       'src_warehouse_id' => $form->{warehouse_id},
579       'transfer_type_id' => $form->{transfer_type_id},
580     };
581
582     map { $transfer->{$_} = $form->{"${_}_${row}"} } qw(src_bin_id chargenumber bestbefore parts_id qty);
583
584     my $entry;
585
586     foreach (@contents) {
587       if (($_->{binid} == $transfer->{src_bin_id}) && ($_->{parts_id} == $transfer->{parts_id}) && ($_->{chargenumber} eq $transfer->{chargenumber}) && ($_->{bestbefore} eq $transfer->{bestbefore})) {
588         $entry = $_;
589         last;
590       }
591     }
592
593     if (!$entry) {
594       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
595                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
596     }
597
598     $transfer->{qty}  = $form->parse_amount(\%myconfig, $transfer->{qty}) * $all_units->{$form->{"unit_$row"}}->{factor};
599     $transfer->{qty} /= $all_units->{$entry->{partunit}}->{factor} || 1;
600
601     if (($entry->{qty} < $transfer->{qty}) || (0 >= $transfer->{qty})) {
602       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
603                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
604     }
605
606     $transfer->{comment} = $form->{comment};
607
608     push @transfers, $transfer;
609
610     $entry->{qty} -= $transfer->{qty};
611   }
612
613   if (!scalar @transfers) {
614     $form->show_generic_information($locale->text('Nothing has been selected for removal.'));
615     ::end_of_request();
616   }
617
618   WH->transfer(@transfers);
619
620   $form->{trans_type}    = 'removal';
621   $form->{saved_message} = $locale->text('The parts have been removed.');
622
623   transfer_warehouse_selection();
624
625   $main::lxdebug->leave_sub();
626 }
627
628 # --------------------------------------------------------------------
629 # Journal
630 # --------------------------------------------------------------------
631
632 sub journal {
633   $main::lxdebug->enter_sub();
634
635   $main::auth->assert('warehouse_management');
636
637   my $form     = $main::form;
638   my %myconfig = %main::myconfig;
639   my $locale   = $main::locale;
640
641   $form->{title} = $locale->text('Report about warehouse transactions');
642   $form->get_lists('warehouses' => { 'key'  => 'WAREHOUSES',
643                                      'bins' => 'BINS', });
644
645   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
646
647   $form->{jsscript} = 1;
648
649   $form->header();
650   print $form->parse_html_template("wh/journal_filter", { "UNITS" => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
651
652   $main::lxdebug->leave_sub();
653 }
654
655 sub generate_journal {
656   $main::lxdebug->enter_sub();
657
658   $main::auth->assert('warehouse_management');
659
660   my $form     = $main::form;
661   my %myconfig = %main::myconfig;
662   my $locale   = $main::locale;
663
664   $form->{title}   = $locale->text("WHJournal");
665   $form->{sort}  ||= 'date';
666
667   my %filter;
668   my @columns = qw(trans_id date warehouse_from bin_from warehouse_to bin_to partnumber partdescription chargenumber bestbefore trans_type comment qty employee oe_id projectnumber);
669
670   # filter stuff
671   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id partnumber description chargenumber bestbefore);
672
673   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
674   if ($filter{qty_op}) {
675     $form->isblank("qty",      $locale->text('Quantity missing.'));
676     $form->isblank("qty_unit", $locale->text('Unit missing.'));
677
678     $filter{qty}      = $form->{qty};
679     $filter{qty_unit} = $form->{qty_unit};
680   }
681   # /filter stuff
682
683   my $report = SL::ReportGenerator->new(\%myconfig, $form);
684
685   my @hidden_variables = map { "l_${_}" } @columns;
686   push @hidden_variables, qw(warehouse_id bin_id partnumber description chargenumber bestbefore qty_op qty qty_unit fromdate todate);
687
688   my %column_defs = (
689     'date'            => { 'text' => $locale->text('Date'), },
690     'trans_id'        => { 'text' => $locale->text('Trans Id'), },
691     'trans_type'      => { 'text' => $locale->text('Trans Type'), },
692     'comment'         => { 'text' => $locale->text('Comment'), },
693     'warehouse_from'  => { 'text' => $locale->text('Warehouse From'), },
694     'warehouse_to'    => { 'text' => $locale->text('Warehouse To'), },
695     'bin_from'        => { 'text' => $locale->text('Bin From'), },
696     'bin_to'          => { 'text' => $locale->text('Bin To'), },
697     'partnumber'      => { 'text' => $locale->text('Part Number'), },
698     'partdescription' => { 'text' => $locale->text('Part Description'), },
699     'chargenumber'    => { 'text' => $locale->text('Charge Number'), },
700     'bestbefore'      => { 'text' => $locale->text('Best Before'), },
701     'qty'             => { 'text' => $locale->text('Qty'), },
702     'employee'        => { 'text' => $locale->text('Employee'), },
703     'projectnumber'   => { 'text' => $locale->text('Project Number'), },
704     'oe_id'           => { 'text' => $locale->text('Document'), },
705   );
706
707   my $href = build_std_url('action=generate_journal', grep { $form->{$_} } @hidden_variables);
708   map { $column_defs{$_}->{link} = $href . "&sort=${_}&order=" . Q($_ eq $form->{sort} ? 1 - $form->{order} : $form->{order}) } @columns;
709
710   my %column_alignment = map { $_ => 'right' } qw(qty);
711
712   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
713
714   $report->set_columns(%column_defs);
715   $report->set_column_order(@columns);
716
717   $report->set_export_options('generate_journal', @hidden_variables, qw(sort order));
718
719   $report->set_sort_indicator($form->{sort}, $form->{order});
720
721   $report->set_options('output_format'        => 'HTML',
722                        'title'                => $form->{title},
723                        'attachment_basename'  => strftime($locale->text('warehouse_journal_list') . '_%Y%m%d', localtime time));
724   $report->set_options_from_form();
725   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
726
727   my $all_units = AM->retrieve_units(\%myconfig, $form);
728   my @contents  = WH->get_warehouse_journal(%filter);
729
730   my %doc_types = ( 'sales_quotation'         => { script => 'oe', title => $locale->text('Sales quotation') },
731                     'sales_order'             => { script => 'oe', title => $locale->text('Sales Order') },
732                     'request_quotation'       => { script => 'oe', title => $locale->text('Request quotation') },
733                     'purchase_order'          => { script => 'oe', title => $locale->text('Purchase Order') },
734                     'sales_delivery_order'    => { script => 'do', title => $locale->text('Sales delivery order') },
735                     'purchase_delivery_order' => { script => 'do', title => $locale->text('Purchase delivery order') },
736                     'sales_invoice'           => { script => 'is', title => $locale->text('Sales Invoice') },
737                     'purchase_invoice'        => { script => 'ir', title => $locale->text('Purchase Invoice') },
738                   );
739
740   foreach my $entry (@contents) {
741     $entry->{qty}        = $form->format_amount_units('amount'     => $entry->{qty},
742                                                       'part_unit'  => $entry->{partunit},
743                                                       'conv_units' => 'convertible');
744     $entry->{trans_type} = $locale->text($entry->{trans_type});
745
746     my $row = { };
747
748     foreach my $column (@columns) {
749       $row->{$column} = {
750         'data'  => $entry->{$column},
751         'align' => $column_alignment{$column},
752       };
753     }
754
755     $row->{trans_type}->{raw_data} = $entry->{trans_type};
756
757     if ($form->{l_oe_id}) {
758       $row->{oe_id}->{data} = '';
759       my $info              = $entry->{oe_id_info};
760
761       if ($info && $info->{id} && $info->{type} && $doc_types{$info->{type}}) {
762         $row->{oe_id} = { data => $doc_types{ $info->{type} }->{title} . ' ' . $info->{number},
763                           link => build_std_url('script=' . $doc_types{ $info->{type} }->{script} . '.pl', 'action=edit', 'id=' . $info->{id}, 'type=' . $info->{type}) };
764       }
765     }
766
767     $report->add_data($row);
768   }
769
770   $report->generate_with_headers();
771
772   $main::lxdebug->leave_sub();
773 }
774
775 # --------------------------------------------------------------------
776 # Report
777 # --------------------------------------------------------------------
778
779 sub report {
780   $main::lxdebug->enter_sub();
781
782   $main::auth->assert('warehouse_contents | warehouse_management');
783
784   my $form     = $main::form;
785   my %myconfig = %main::myconfig;
786   my $locale   = $main::locale;
787
788   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
789                                      'bins'   => 'BINS', });
790
791   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
792
793   $form->{jsscript} = 1;
794
795 #  $form->{fokus}   = "partnumber";
796 #  $form->{onload} .= "focus();";
797   $form->{title}   = $locale->text("Report about warehouse contents");
798
799   $form->header();
800   print $form->parse_html_template("wh/report_filter",
801                                    { "nextsub"    => "generate_report",
802                                      "WAREHOUSES" => $form->{WAREHOUSES},
803                                      "UNITS"      => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
804
805   $main::lxdebug->leave_sub();
806 }
807
808 sub generate_report {
809   $main::lxdebug->enter_sub();
810
811   $main::auth->assert('warehouse_contents | warehouse_management');
812
813   my $form     = $main::form;
814   my %myconfig = %main::myconfig;
815   my $locale   = $main::locale;
816
817   $form->{title}   = $locale->text("Report about warehouse contents");
818   $form->{sort}  ||= 'partnumber';
819   my $sort_col     = $form->{sort};
820
821   my %filter;
822   my @columns = qw(warehousedescription bindescription partnumber partdescription chargenumber bestbefore qty stock_value);
823
824   # filter stuff
825   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id partnumber description chargenumber bestbefore);
826
827   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
828   if ($filter{qty_op}) {
829     $form->isblank("qty",      $locale->text('Quantity missing.'));
830     $form->isblank("qty_unit", $locale->text('Unit missing.'));
831
832     $filter{qty}      = $form->{qty};
833     $filter{qty_unit} = $form->{qty_unit};
834   }
835   # /filter stuff
836
837   $form->{subtotal} = '' if (!first { $_ eq $sort_col } qw(partnumber partdescription));
838
839   my $report = SL::ReportGenerator->new(\%myconfig, $form);
840
841   my @hidden_variables = map { "l_${_}" } @columns;
842   push @hidden_variables, qw(warehouse_id bin_id partnumber description chargenumber bestbefore qty_op qty qty_unit l_warehousedescription l_bindescription);
843   push @hidden_variables, qw(include_empty_bins subtotal);
844
845   my %column_defs = (
846     'warehousedescription' => { 'text' => $locale->text('Warehouse'), },
847     'bindescription'       => { 'text' => $locale->text('Bin'), },
848     'partnumber'           => { 'text' => $locale->text('Part Number'), },
849     'partdescription'      => { 'text' => $locale->text('Part Description'), },
850     'chargenumber'         => { 'text' => $locale->text('Charge Number'), },
851     'bestbefore'           => { 'text' => $locale->text('Best Before'), },
852     'qty'                  => { 'text' => $locale->text('Qty'), },
853     'stock_value'          => { 'text' => $locale->text('Stock value'), },
854   );
855
856   my $href = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
857   map { $column_defs{$_}->{link} = $href . "&sort=${_}&order=" . Q($_ eq $sort_col ? 1 - $form->{order} : $form->{order}) } @columns;
858
859   my %column_alignment = map { $_ => 'right' } qw(qty stock_value);
860
861   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
862
863   $report->set_columns(%column_defs);
864   $report->set_column_order(@columns);
865
866   $report->set_export_options('generate_report', @hidden_variables, qw(sort order));
867
868   $report->set_sort_indicator($sort_col, $form->{order});
869
870   $report->set_options('output_format'        => 'HTML',
871                        'title'                => $form->{title},
872                        'attachment_basename'  => strftime($locale->text('warehouse_report_list') . '_%Y%m%d', localtime time));
873   $report->set_options_from_form();
874   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
875
876   my $all_units = AM->retrieve_units(\%myconfig, $form);
877   my @contents  = WH->get_warehouse_report(%filter);
878
879   my $idx       = 0;
880
881   my @subtotals_columns = qw(qty stock_value);
882   my %subtotals         = map { $_ => 0 } @subtotals_columns;
883
884   my $total_stock_value = 0;
885
886   foreach my $entry (@contents) {
887     map { $subtotals{$_} += $entry->{$_} } @subtotals_columns;
888     $total_stock_value   += $entry->{stock_value} * 1;
889
890     $entry->{qty}         = $form->format_amount_units('amount'     => $entry->{qty},
891                                                        'part_unit'  => $entry->{partunit},
892                                                        'conv_units' => 'convertible');
893     $entry->{stock_value} = $form->format_amount(\%myconfig, $entry->{stock_value} * 1, 2);
894
895     my $row_set = [ { map { $_ => { 'data' => $entry->{$_}, 'align' => $column_alignment{$_} } } @columns } ];
896
897     if (($form->{subtotal} eq 'Y')
898         && (($idx == (scalar @contents - 1))
899             || ($entry->{$sort_col} ne $contents[$idx + 1]->{$sort_col}))) {
900
901       my $row = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', 'align' => $column_alignment{$_}, } } @columns };
902       $row->{qty}->{data}         = $form->format_amount_units('amount'     => $subtotals{qty} * 1,
903                                                                'part_unit'  => $entry->{partunit},
904                                                                'conv_units' => 'convertible');
905       $row->{stock_value}->{data} = $form->format_amount(\%myconfig, $subtotals{stock_value} * 1, 2);
906
907       %subtotals                  = map { $_ => 0 } @subtotals_columns;
908
909       push @{ $row_set }, $row;
910     }
911
912     $report->add_data($row_set);
913
914     $idx++;
915   }
916
917   if ($column_defs{stock_value}->{visible}) {
918     $report->add_separator();
919
920     my $row                      = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', } } @columns };
921
922     my $left_col                 = first { $column_defs{$_}->{visible} } @columns;
923
924     $row->{$left_col}->{data}    = $locale->text('Total stock value');
925     $row->{stock_value}->{data}  = $form->format_amount(\%myconfig, $total_stock_value, 2);
926     $row->{stock_value}->{align} = 'right';
927
928     $report->add_data($row);
929   }
930
931   $report->generate_with_headers();
932
933   $main::lxdebug->leave_sub();
934 }
935
936 # --------------------------------------------------------------------
937 # Utility functions
938 # --------------------------------------------------------------------
939
940 sub show_no_warehouses_error {
941   $main::lxdebug->enter_sub();
942
943   my $form     = $main::form;
944   my %myconfig = %main::myconfig;
945   my $locale   = $main::locale;
946
947   my $msg = $locale->text('No warehouse has been created yet or the quantity of the bins is not configured yet.') . ' ';
948
949   if ($main::auth->check_right($form->{login}, 'config')) {
950     $msg .= $locale->text('You can create warehouses and bins via the menu "System -> Warehouses".');
951   } else {
952     $msg .= $locale->text('Please ask your administrator to create warehouses and bins.');
953   }
954
955   $form->show_generic_error($msg);
956
957   $main::lxdebug->leave_sub();
958 }
959
960 sub get_warehouse_idx {
961   my ($warehouse_id) = @_;
962
963   my $form     = $main::form;
964
965   for (my $i = 0; $i < scalar @{$form->{WAREHOUSES}}; $i++) {
966     return $i if ($form->{WAREHOUSES}->[$i]->{id} == $warehouse_id);
967   }
968
969   return -1;
970 }
971
972 sub get_bin_idx {
973   my ($warehouse_index, $bin_id) = @_;
974
975   my $form     = $main::form;
976
977   my $warehouse = $form->{WAREHOUSES}->[$warehouse_index];
978
979   return -1 if (!$warehouse);
980
981   for (my $i = 0; $i < scalar @{ $warehouse->{BINS} }; $i++) {
982     return $i if ($warehouse->{BINS}->[$i]->{id} == $bin_id);
983   }
984
985   return -1;
986 }
987
988 sub new_item {
989   $main::lxdebug->enter_sub();
990   my %params = @_;
991
992   my $form     = $main::form;
993
994   # change callback
995   $form->{old_callback} = $form->escape($form->{callback}, 1);
996   $form->{callback}     = $form->escape("$form->{script}?action=$params{action}", 1);
997
998   # save all form variables except action in a previousform variable
999   my $previousform = join '&', map { my $value = $form->{$_}; $value =~ s/&/%26/; "$_=$value" } grep { !/action/ } keys %$form;
1000   my @HIDDENS = ();
1001
1002 #  push @HIDDENS,      { 'name' => 'previousform', 'value' => $form->escape($previousform, 1) };
1003   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} }, qw(partnumber description unit vc sellprice ean);
1004   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
1005   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{longdescription} };
1006
1007   $form->header();
1008   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
1009
1010   $main::lxdebug->leave_sub();
1011 }
1012
1013 sub update {
1014   my $form     = $main::form;
1015   call_sub($form->{update_nextsub} || $form->{nextsub});
1016 }
1017
1018 sub continue {
1019   my $form     = $main::form;
1020   call_sub($form->{continue_nextsub} || $form->{nextsub});
1021 }
1022
1023 sub stock {
1024   my $form     = $main::form;
1025   call_sub($form->{stock_nextsub} || $form->{nextsub});
1026 }
1027
1028 1;
1029
1030 __END__
1031
1032 =head1 NAME
1033
1034 bin/mozilla/wh.pl - Warehouse frontend.
1035
1036 =head1 FUNCTIONS
1037
1038 =over 4
1039
1040 =item new_item
1041
1042 call new item dialogue from warehouse masks.
1043
1044 PARAMS:
1045   action  => name of sub to be called when new item is done
1046
1047 =back
1048
1049 =cut