d632d5d961962e29e47b22726ce44c882b1311d1
[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 # parserhappy(R):
53
54 # contents of the "transfer_type" table:
55 #  $locale->text('back')
56 #  $locale->text('correction')
57 #  $locale->text('disposed')
58 #  $locale->text('found')
59 #  $locale->text('missing')
60 #  $locale->text('stock')
61 #  $locale->text('shipped')
62 #  $locale->text('transfer')
63 #  $locale->text('used')
64 #  $locale->text('return_material')
65 #  $locale->text('release_material')
66
67 # --------------------------------------------------------------------
68 # Transfer
69 # --------------------------------------------------------------------
70
71 sub transfer_warehouse_selection {
72   $lxdebug->enter_sub();
73
74   $auth->assert('warehouse_management');
75
76   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
77                                      'bins'   => 'BINS', });
78
79   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
80
81   my $units      = AM->retrieve_units(\%myconfig, $form);
82   $form->{UNITS} = AM->unit_select_data($units, $form->{unit}, 0, $form->{partunit});
83
84   if (scalar @{ $form->{WAREHOUSES} }) {
85     $form->{warehouse_id} ||= $form->{WAREHOUSES}->[0]->{id};
86     $form->{bin_id}       ||= $form->{WAREHOUSES}->[0]->{BINS}->[0]->{id};
87   }
88
89   my $content;
90
91   $form->{jsscript} = 1;
92
93   if ($form->{trans_type} eq 'removal') {
94     $form->{nextsub} = "removal_parts_selection";
95     $form->{title}   = $locale->text('Removal from Warehouse');
96     $content         = $form->parse_html_template('wh/warehouse_selection');
97
98   } elsif ($form->{trans_type} eq 'stock') {
99     $form->{title} = $locale->text('Stock');
100     $content       = $form->parse_html_template('wh/warehouse_selection_stock');
101
102   } elsif (!$form->{trans_type} || ($form->{trans_type} eq 'transfer')) {
103     $form->{nextsub} = "transfer_parts_selection";
104     $form->{title}   = $locale->text('Transfer');
105     $content         = $form->parse_html_template('wh/warehouse_selection');
106
107   } elsif ($form->{trans_type} eq 'assembly') {
108     $form->{title} = $locale->text('Produce Assembly');
109     $content       = $form->parse_html_template('wh/warehouse_selection_assembly');
110   }
111
112   $form->header();
113   print $content;
114
115   $lxdebug->leave_sub();
116 }
117
118 sub transfer_parts_selection {
119   $lxdebug->enter_sub();
120
121   $auth->assert('warehouse_management');
122
123   transfer_or_removal_prepare_contents('direction' => 'transfer');
124
125   $form->{title} = $locale->text('Transfer');
126   $form->header();
127   print $form->parse_html_template("wh/transfer_parts_selection");
128
129   $lxdebug->leave_sub();
130 }
131
132 sub transfer_or_removal_prepare_contents {
133   $lxdebug->enter_sub();
134
135   $auth->assert('warehouse_management');
136
137   my %args = @_;
138
139   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
140                                      'bins'   => 'BINS', });
141
142   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
143   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
144
145   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
146
147   $form->{initial_warehouse_idx} = $warehouse_idx;
148   $form->{warehouse_description} = $warehouse->{description};
149   $warehouse->{selected}         = 1;
150
151   $form->show_generic_error($locale->text("The source warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
152
153   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber partunit ean);
154
155   $form->{sort} = 'bindescription';
156   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id},
157                                            "bin_id"       => $form->{bin_id},
158                                            "chargenumber" => $form->{chargenumber},
159                                            "partnumber"   => $form->{partnumber},
160                                            "ean"          => $form->{ean},
161                                            "description"  => $form->{description});
162
163   $form->show_generic_error($locale->text("The selected warehouse is empty.")) if (0 == scalar(@contents));
164
165   my $all_units = AM->retrieve_units(\%myconfig, $form);
166
167   foreach (@contents) {
168     $_->{qty} = $form->format_amount_units('amount'     => $_->{qty},
169                                            'part_unit'  => $_->{partunit},
170                                            'conv_units' => 'convertible');
171     my $this_unit = $_->{partunit};
172
173     if ($all_units->{$_->{partunit}} && ($all_units->{g}->{base_unit} eq $all_units->{$_->{partunit}}->{base_unit})) {
174       $this_unit = "kg";
175     }
176
177     $_->{UNITS} = AM->unit_select_data($all_units, $this_unit, 0, $_->{partunit});
178   }
179
180   my $transfer_types = WH->retrieve_transfer_types($args{direction});
181   map { $_->{description} = $locale->text($_->{description}) } @{ $transfer_types };
182
183   $form->{CONTENTS}       = \@contents;
184   $form->{TRANSFER_TYPES} = $transfer_types;
185
186   $lxdebug->leave_sub();
187 }
188
189
190 sub transfer_parts {
191   $lxdebug->enter_sub();
192
193   $auth->assert('warehouse_management');
194
195   $form->get_lists('warehouses' => { 'key' => 'WAREHOUSES', 'bins' => 'BINS' });
196
197   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
198   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
199
200   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
201
202   $form->show_generic_error($locale->text("The source warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
203
204   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber partunit);
205
206   $form->{sort} = 'bindescription';
207   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id});
208   my $all_units = AM->retrieve_units(\%myconfig, $form);
209
210   my @transfers;
211
212   foreach my $row (1 .. $form->{rowcount}) {
213     $form->{"qty_$row"} =~ s/^\s*//;
214     $form->{"qty_$row"} =~ s/\s*$//;
215     next if (!$form->{"qty_$row"});
216
217     my $bin_idx = get_bin_idx($warehouse_idx, $form->{"src_bin_id_$row"});
218     $form->show_generic_error($locale->text("The selected bin does not exist.")) if (-1 == $bin_idx);
219     my $bin     = $warehouse->{BINS}->[$bin_idx];
220
221     my $orig_qty = $form->{"qty_$row"} . " " . $form->{"unit_$row"};
222
223     my $transfer = {
224       'src_warehouse_id' => $form->{warehouse_id},
225       'transfer_type_id' => $form->{transfer_type_id},
226     };
227
228     map { $transfer->{$_} = $form->{"${_}_${row}"} } qw(src_bin_id chargenumber parts_id qty dst_warehouse_id dst_bin_id);
229
230     my $entry;
231
232     foreach (@contents) {
233       if (($_->{binid} == $transfer->{src_bin_id}) && ($_->{parts_id} == $transfer->{parts_id}) && ($_->{chargenumber} eq $transfer->{chargenumber})) {
234         $entry = $_;
235         last;
236       }
237     }
238
239     if (!$entry) {
240       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
241                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
242     }
243
244     $transfer->{qty}  = $form->parse_amount(\%myconfig, $transfer->{qty}) * $all_units->{$form->{"unit_$row"}}->{factor};
245     $transfer->{qty} /= $all_units->{$entry->{partunit}}->{factor} || 1;
246
247     if (($entry->{qty} < $transfer->{qty}) || (0 >= $transfer->{qty})) {
248       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
249                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
250     }
251
252     $transfer->{comment} = $form->{comment};
253
254     push @transfers, $transfer;
255
256     $entry->{qty} -= $transfer->{qty};
257   }
258
259   if (!scalar @transfers) {
260     $form->show_generic_information($locale->text('Nothing has been selected for transfer.'));
261     exit 0;
262   }
263
264   WH->transfer(@transfers);
265
266   $form->{trans_type}    = 'transfer';
267   $form->{saved_message} = $locale->text('The parts have been transferred.');
268
269   transfer_warehouse_selection();
270
271   $lxdebug->leave_sub();
272 }
273
274 # --------------------------------------------------------------------
275 # Transfer: stock
276 # --------------------------------------------------------------------
277
278 sub transfer_stock_update_part {
279   $lxdebug->enter_sub();
280
281   $form->{trans_type} = 'stock';
282   $form->{qty}        = $form->parse_amount(\%myconfig, $form->{qty});
283
284   if (!$form->{partnumber} && !$form->{description} && !$form->{ean}) {
285     delete @{$form}{qw(parts_id partunit ean)};
286     transfer_warehouse_selection();
287
288   } elsif (($form->{partnumber} && ($form->{partnumber} ne $form->{old_partnumber})) || $form->{description} || $form->{ean}) {
289
290     $form->{no_services}   = 1;
291     $form->{no_assemblies} = 0; # assemblies duerfen eingelagert werden (z.B. bei retouren)
292
293     my $parts = Common->retrieve_parts(\%myconfig, $form, 'description', 1);
294
295     if (scalar @{ $parts } == 1) {
296       @{$form}{qw(parts_id partnumber description ean)} = @{$parts->[0]}{qw(id partnumber description ean)};
297       transfer_stock_get_partunit();
298       transfer_warehouse_selection();
299
300     } else {
301       select_part('transfer_stock_part_selected', @{ $parts });
302     }
303
304   } else {
305     transfer_stock_get_partunit();
306     transfer_warehouse_selection();
307   }
308
309   $lxdebug->leave_sub();
310 }
311
312 # --------------------------------------------------------------------
313 # Transfer: assemblies
314 # Dies ist die Auswahlmaske für ein assembly. 
315 # Die ist einfach von transfer_assembly_update_part kopiert und nur um den trans_type (assembly) korrigiert worden
316 # Es wäre schön, hier nochmal check_assembly_max_create auf, um die max. Fertigungszahl herauszufinden.
317 # Ich lass das mal als auskommentierte Idee bestehen jb 18.3.09
318 # --------------------------------------------------------------------
319
320 sub transfer_assembly_update_part {
321   $lxdebug->enter_sub();
322
323   $form->{trans_type} = 'assembly';
324   $form->{qty}        = $form->parse_amount(\%myconfig, $form->{qty});
325
326   if (!$form->{partnumber} && !$form->{description}) {
327     delete @{$form}{qw(parts_id partunit)};
328     transfer_warehouse_selection();
329
330   } elsif (($form->{partnumber} && ($form->{partnumber} ne $form->{old_partnumber})) || $form->{description}) {
331     $form->{assemblies} = 1;
332     $form->{no_assemblies} = 0;
333     my $parts = Common->retrieve_parts(\%myconfig, $form, 'description', 1);
334     if (scalar @{ $parts } == 1) {
335       @{$form}{qw(parts_id partnumber description)} = @{$parts->[0]}{qw(id partnumber description)};
336       transfer_stock_get_partunit();
337       transfer_warehouse_selection();
338     } else {
339       select_part('transfer_stock_part_selected', @{ $parts });
340     }
341
342   } else {
343     transfer_stock_get_partunit();
344     transfer_warehouse_selection();
345   }
346
347 # hier die oben benannte idee
348 #    my $maxcreate = Common->check_assembly_max_create(assembly_id => $form->{parts_id}, dbh => $my_dbh); 
349   $lxdebug->leave_sub();
350 }
351 sub transfer_stock_part_selected {
352   $lxdebug->enter_sub();
353
354   my $part = shift;
355
356   @{$form}{qw(parts_id partnumber description ean)} = @{$part}{qw(id partnumber description ean)};
357
358   transfer_stock_get_partunit();
359   transfer_warehouse_selection();
360
361   $lxdebug->leave_sub();
362 }
363
364 sub transfer_stock_get_partunit {
365   $lxdebug->enter_sub();
366
367   if ($form->{parts_id}) {
368     my $part_info     = IC->get_basic_part_info('id' => $form->{parts_id});
369     $form->{partunit} = $part_info->{unit};
370   }
371
372   $lxdebug->leave_sub();
373 }
374
375 # vorüberlegung jb 22.2.2009
376 # wir benötigen für diese funktion, die anzahl die vom erzeugnis hergestellt werden soll. vielleicht direkt per js fehleingaben verhindern?
377 # ferner dann nochmal mit check_asssembly_max_create gegenprüfen und dann transaktionssicher wegbuchen.
378 # 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
379 # Manko ist derzeit noch, dass unterschiedliche Lagerplätze, bzw. das Quelllager an sich nicht ausgewählt werden können.
380 # Laut Absprache in KW11 09 Ã¼bernimmt mb hier den rest im April ... jb 18.3.09
381
382 sub create_assembly {
383   $lxdebug->enter_sub();
384
385   $form->{qty} = $form->parse_amount(\%myconfig, $form->{qty});
386   if ($form->{qty} <= 0) {
387     $form->show_generic_error($locale->text('Invalid quantity.'), 'back_button' => 1);
388   }
389   # TODO Es wäre schön, hier schon die maximale Anzahl der zu fertigenden Erzeugnisse zu haben  
390   #else { if ($form->{qty} > $maxcreate) {      #s.o.
391   #         $form->show_generic_error($locale->text('Can not create that quantity with current stock'), 'back_button' => 1);
392   #         $form->show_generic_error('Maximale Stückzahl' . $maxcreate , 'back_button' => 1);
393   #       } 
394   #  }
395
396   if (!$form->{warehouse_id} || !$form->{bin_id}) {
397     $form->error($locale->text('The warehouse or the bin is missing.'));
398   }
399   # 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
400   # Anm. jb 18.3. vielleicht auch nur meine unwissenheit in perl-datenstrukturen
401   my %TRANSFER = (
402     'transfer_type'    => 'assembly',
403     'login'     => $form->{login},
404     'dst_warehouse_id' => $form->{warehouse_id},
405     'dst_bin_id'       => $form->{bin_id},
406     'chargenumber'     => $form->{chargenumber},
407     'assembly_id'         => $form->{parts_id},
408     'qty'              => $form->{qty},
409     'unit'             => $form->{unit},
410     'comment'          => $form->{comment}
411   );
412
413   my $ret = WH->transfer_assembly (%TRANSFER);
414   # Frage: Ich pack in den return-wert auch gleich die Fehlermeldung. Irgendwelche Nummern als Fehlerkonstanten definieren find ich auch nicht besonders schick...
415   # Ideen? jb 18.3.09
416   if ($ret ne "1"){
417     # 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
418     $form->show_generic_error($ret, 'back_button' => 1);
419   }
420
421   delete @{$form}{qw(parts_id partnumber description qty unit chargenumber comment)};
422
423   $form->{saved_message} = $locale->text('The assembly has been created.');
424   $form->{trans_type}    = 'assembly';
425
426   transfer_warehouse_selection();
427
428   $lxdebug->leave_sub();
429 }
430
431 sub transfer_stock {
432   $lxdebug->enter_sub();
433
434   $form->{qty} = $form->parse_amount(\%myconfig, $form->{qty});
435
436   if ($form->{qty} <= 0) {
437     $form->show_generic_error($locale->text('Invalid quantity.'), 'back_button' => 1);
438   }
439
440   if (!$form->{warehouse_id} || !$form->{bin_id}) {
441     $form->error($locale->text('The warehouse or the bin is missing.'));
442   }
443
444   my $transfer = {
445     'transfer_type'    => 'stock',
446     'dst_warehouse_id' => $form->{warehouse_id},
447     'dst_bin_id'       => $form->{bin_id},
448     'chargenumber'     => $form->{chargenumber},
449     'parts_id'         => $form->{parts_id},
450     'qty'              => $form->{qty},
451     'unit'             => $form->{unit},
452     'comment'          => $form->{comment},
453   };
454
455   WH->transfer($transfer);
456
457   delete @{$form}{qw(parts_id partnumber description qty unit chargenumber comment)};
458
459   $form->{saved_message} = $locale->text('The parts have been stocked.');
460   $form->{trans_type}    = 'stock';
461
462   transfer_warehouse_selection();
463
464   $lxdebug->leave_sub();
465 }
466
467 # --------------------------------------------------------------------
468 # Transfer: removal
469 # --------------------------------------------------------------------
470
471 sub removal_parts_selection {
472   $lxdebug->enter_sub();
473
474   $auth->assert('warehouse_management');
475
476   transfer_or_removal_prepare_contents('direction' => 'out');
477
478   $form->{title} = $locale->text('Removal');
479   $form->header();
480   print $form->parse_html_template("wh/removal_parts_selection");
481
482   $lxdebug->leave_sub();
483 }
484
485 sub remove_parts {
486   $lxdebug->enter_sub();
487
488   $auth->assert('warehouse_management');
489
490   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
491                                      'bins'   => 'BINS', });
492
493   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
494   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
495
496   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
497
498   $form->show_generic_error($locale->text("The warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
499
500   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber partunit);
501
502   $form->{sort} = 'bindescription';
503   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id});
504   my $all_units = AM->retrieve_units(\%myconfig, $form);
505
506   my @transfers;
507
508   foreach my $row (1 .. $form->{rowcount}) {
509     $form->{"qty_$row"} =~ s/^\s*//;
510     $form->{"qty_$row"} =~ s/\s*$//;
511     next if (!$form->{"qty_$row"});
512
513     my $bin_idx = get_bin_idx($warehouse_idx, $form->{"src_bin_id_$row"});
514     $form->show_generic_error($locale->text("The selected bin does not exist.")) if (-1 == $bin_idx);
515     my $bin     = $warehouse->{BINS}->[$bin_idx];
516
517     my $orig_qty = $form->{"qty_$row"} . " " . $form->{"unit_$row"};
518
519     my $transfer = {
520       'src_warehouse_id' => $form->{warehouse_id},
521       'transfer_type_id' => $form->{transfer_type_id},
522     };
523
524     map { $transfer->{$_} = $form->{"${_}_${row}"} } qw(src_bin_id chargenumber parts_id qty);
525
526     my $entry;
527
528     foreach (@contents) {
529       if (($_->{binid} == $transfer->{src_bin_id}) && ($_->{parts_id} == $transfer->{parts_id}) && ($_->{chargenumber} eq $transfer->{chargenumber})) {
530         $entry = $_;
531         last;
532       }
533     }
534
535     if (!$entry) {
536       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
537                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
538     }
539
540     $transfer->{qty}  = $form->parse_amount(\%myconfig, $transfer->{qty}) * $all_units->{$form->{"unit_$row"}}->{factor};
541     $transfer->{qty} /= $all_units->{$entry->{partunit}}->{factor} || 1;
542
543     if (($entry->{qty} < $transfer->{qty}) || (0 >= $transfer->{qty})) {
544       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
545                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
546     }
547
548     $transfer->{comment} = $form->{comment};
549
550     push @transfers, $transfer;
551
552     $entry->{qty} -= $transfer->{qty};
553   }
554
555   if (!scalar @transfers) {
556     $form->show_generic_information($locale->text('Nothing has been selected for removal.'));
557     exit 0;
558   }
559
560   WH->transfer(@transfers);
561
562   $form->{trans_type}    = 'removal';
563   $form->{saved_message} = $locale->text('The parts have been removed.');
564
565   transfer_warehouse_selection();
566
567   $lxdebug->leave_sub();
568 }
569
570 # --------------------------------------------------------------------
571 # Journal
572 # --------------------------------------------------------------------
573
574 sub journal {
575   $lxdebug->enter_sub();
576
577   $auth->assert('warehouse_management');
578
579   $form->get_lists('warehouses' => { 'key'  => 'WAREHOUSES',
580                                      'bins' => 'BINS', });
581
582   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
583
584   $form->{jsscript} = 1;
585
586   $form->header();
587   print $form->parse_html_template("wh/journal_filter", { "UNITS" => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
588
589   $lxdebug->leave_sub();
590 }
591
592 sub generate_journal {
593   $lxdebug->enter_sub();
594
595   $auth->assert('warehouse_management');
596
597   $form->{title}   = $locale->text("WHJournal");
598   $form->{sort}  ||= 'date';
599
600   my %filter;
601   my @columns = qw(trans_id date warehouse_from bin_from warehouse_to bin_to partnumber partdescription chargenumber trans_type comment qty employee projectnumber);
602
603   # filter stuff
604   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id partnumber description chargenumber);
605
606   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
607   if ($filter{qty_op}) {
608     $form->isblank(qty,      $locale->text('Quantity missing.'));
609     $form->isblank(qty_unit, $locale->text('Unit missing.'));
610
611     $filter{qty}      = $form->{qty};
612     $filter{qty_unit} = $form->{qty_unit};
613   }
614   # /filter stuff
615
616   my $report = SL::ReportGenerator->new(\%myconfig, $form);
617
618   my @hidden_variables = map { "l_${_}" } @columns;
619   push @hidden_variables, qw(warehouse_id bin_id partnumber description chargenumber qty_op qty qty_unit fromdate todate);
620
621   my %column_defs = (
622     'date'            => { 'text' => $locale->text('Date'), },
623     'trans_id'        => { 'text' => $locale->text('Trans Id'), },
624     'trans_type'      => { 'text' => $locale->text('Trans Type'), },
625     'comment'         => { 'text' => $locale->text('Comment'), },
626     'warehouse_from'  => { 'text' => $locale->text('Warehouse From'), },
627     'warehouse_to'    => { 'text' => $locale->text('Warehouse To'), },
628     'bin_from'        => { 'text' => $locale->text('Bin From'), },
629     'bin_to'          => { 'text' => $locale->text('Bin To'), },
630     'partnumber'      => { 'text' => $locale->text('Part Number'), },
631     'partdescription' => { 'text' => $locale->text('Description'), },
632     'chargenumber'    => { 'text' => $locale->text('Charge Number'), },
633     'qty'             => { 'text' => $locale->text('Qty'), },
634     'employee'        => { 'text' => $locale->text('Employee'), },
635     'projectnumber'   => { 'text' => $locale->text('Project Number'), },
636   );
637
638   my $href = build_std_url('action=generate_journal', grep { $form->{$_} } @hidden_variables);
639   map { $column_defs{$_}->{link} = $href . "&sort=${_}&order=" . Q($_ eq $form->{sort} ? 1 - $form->{order} : $form->{order}) } @columns;
640
641   my %column_alignment = map { $_ => 'right' } qw(qty);
642
643   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
644
645   $report->set_columns(%column_defs);
646   $report->set_column_order(@columns);
647
648   $report->set_export_options('generate_journal', @hidden_variables, qw(sort order));
649
650   $report->set_sort_indicator($form->{sort}, $form->{order});
651
652   $report->set_options('output_format'        => 'HTML',
653                        'title'                => $form->{title},
654                        'attachment_basename'  => strftime($locale->text('warehouse_journal_list') . '_%Y%m%d', localtime time));
655   $report->set_options_from_form();
656
657   my $all_units = AM->retrieve_units(\%myconfig, $form);
658   my @contents  = WH->get_warehouse_journal(%filter);
659
660   foreach $entry (@contents) {
661     $entry->{qty}        = $form->format_amount_units('amount'     => $entry->{qty},
662                                                       'part_unit'  => $entry->{partunit},
663                                                       'conv_units' => 'convertible');
664     $entry->{trans_type} = $locale->text($entry->{trans_type});
665
666     my $row = { };
667
668     foreach my $column (@columns) {
669       next if ($column eq 'trans_type');
670
671       $row->{$column} = {
672         'data'  => $entry->{$column},
673         'align' => $column_alignment{$column},
674       };
675     }
676
677     $row->{trans_type} = {
678       'raw_data' => $entry->{trans_type},
679       'align'    => $column_alignment{trans_type},
680     };
681
682     $report->add_data($row);
683   }
684
685   $report->generate_with_headers();
686
687   $lxdebug->leave_sub();
688 }
689
690 # --------------------------------------------------------------------
691 # Report
692 # --------------------------------------------------------------------
693
694 sub report {
695   $lxdebug->enter_sub();
696
697   $auth->assert('warehouse_contents | warehouse_management');
698
699   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
700                                      'bins'   => 'BINS', });
701
702   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
703
704   $form->{fokus}   = "partnumber";
705   $form->{onload} .= "focus();";
706   $form->{title}   = $locale->text("Report about wareouse contents");
707
708   $form->header();
709   print $form->parse_html_template("wh/report_filter",
710                                    { "nextsub"    => "generate_report",
711                                      "WAREHOUSES" => $form->{WAREHOUSES},
712                                      "UNITS"      => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
713
714   $lxdebug->leave_sub();
715 }
716
717 sub generate_report {
718   $lxdebug->enter_sub();
719
720   $auth->assert('warehouse_contents | warehouse_management');
721
722   $form->{title}   = $locale->text("Report about wareouse contents");
723   $form->{sort}  ||= 'partnumber';
724   my $sort_col     = $form->{sort};
725
726   my %filter;
727   my @columns = qw(warehousedescription bindescription partnumber partdescription chargenumber qty stock_value);
728
729   # filter stuff
730   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id partnumber description chargenumber);
731
732   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
733   if ($filter{qty_op}) {
734     $form->isblank(qty,      $locale->text('Quantity missing.'));
735     $form->isblank(qty_unit, $locale->text('Unit missing.'));
736
737     $filter{qty}      = $form->{qty};
738     $filter{qty_unit} = $form->{qty_unit};
739   }
740   # /filter stuff
741
742   $form->{subtotal} = '' if (!first { $_ eq $sort_col } qw(partnumber partdescription));
743
744   my $report = SL::ReportGenerator->new(\%myconfig, $form);
745
746   my @hidden_variables = map { "l_${_}" } @columns;
747   push @hidden_variables, qw(warehouse_id bin_id partnumber description chargenumber qty_op qty qty_unit l_warehousedescription l_bindescription);
748   push @hidden_variables, qw(include_empty_bins subtotal);
749
750   my %column_defs = (
751     'warehousedescription' => { 'text' => $locale->text('Warehouse'), },
752     'bindescription'       => { 'text' => $locale->text('Bin'), },
753     'partnumber'           => { 'text' => $locale->text('Part Number'), },
754     'partdescription'      => { 'text' => $locale->text('Description'), },
755     'chargenumber'         => { 'text' => $locale->text('Charge Number'), },
756     'qty'                  => { 'text' => $locale->text('Qty'), },
757     'stock_value'          => { 'text' => $locale->text('Stock value'), },
758   );
759
760   my $href = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
761   map { $column_defs{$_}->{link} = $href . "&sort=${_}&order=" . Q($_ eq $sort_col ? 1 - $form->{order} : $form->{order}) } @columns;
762
763   my %column_alignment = map { $_ => 'right' } qw(qty stock_value);
764
765   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
766
767   $report->set_columns(%column_defs);
768   $report->set_column_order(@columns);
769
770   $report->set_export_options('generate_report', @hidden_variables, qw(sort order));
771
772   $report->set_sort_indicator($sort_col, $form->{order});
773
774   $report->set_options('output_format'        => 'HTML',
775                        'title'                => $form->{title},
776                        'attachment_basename'  => strftime($locale->text('warehouse_report_list') . '_%Y%m%d', localtime time));
777   $report->set_options_from_form();
778
779   my $all_units = AM->retrieve_units(\%myconfig, $form);
780   my @contents  = WH->get_warehouse_report(%filter);
781
782   my $idx       = 0;
783
784   my @subtotals_columns = qw(qty stock_value);
785   my %subtotals         = map { $_ => 0 } @subtotals_columns;
786
787   my $total_stock_value = 0;
788
789   foreach $entry (@contents) {
790     map { $subtotals{$_} += $entry->{$_} } @subtotals_columns;
791     $total_stock_value   += $entry->{stock_value} * 1;
792
793     $entry->{qty}         = $form->format_amount_units('amount'     => $entry->{qty},
794                                                        'part_unit'  => $entry->{partunit},
795                                                        'conv_units' => 'convertible');
796     $entry->{stock_value} = $form->format_amount(\%myconfig, $entry->{stock_value} * 1, 2);
797
798     $row_set = [ { map { $_ => { 'data' => $entry->{$_}, 'align' => $column_alignment{$_} } } @columns } ];
799
800     if (($form->{subtotal} eq 'Y')
801         && (($idx == (scalar @contents - 1))
802             || ($entry->{$sort_col} ne $contents[$idx + 1]->{$sort_col}))) {
803
804       my $row = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', 'align' => $column_alignment{$_}, } } @columns };
805       $row->{qty}->{data}         = $form->format_amount_units('amount'     => $subtotals{qty} * 1,
806                                                                'part_unit'  => $entry->{partunit},
807                                                                'conv_units' => 'convertible');
808       $row->{stock_value}->{data} = $form->format_amount(\%myconfig, $subtotals{stock_value} * 1, 2);
809
810       %subtotals                  = map { $_ => 0 } @subtotals_columns;
811
812       push @{ $row_set }, $row;
813     }
814
815     $report->add_data($row_set);
816
817     $idx++;
818   }
819
820   if ($column_defs{stock_value}->{visible}) {
821     $report->add_separator();
822
823     my $row                      = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', } } @columns };
824
825     my $left_col                 = first { $column_defs{$_}->{visible} } @columns;
826
827     $row->{$left_col}->{data}    = $locale->text('Total stock value');
828     $row->{stock_value}->{data}  = $form->format_amount(\%myconfig, $total_stock_value, 2);
829     $row->{stock_value}->{align} = 'right';
830
831     $report->add_data($row);
832   }
833
834   $report->generate_with_headers();
835
836   $lxdebug->leave_sub();
837 }
838
839 # --------------------------------------------------------------------
840 # Utility functions
841 # --------------------------------------------------------------------
842
843 sub show_no_warehouses_error {
844   $lxdebug->enter_sub();
845
846   my $msg = $locale->text('No warehouse has been created yet or the quantity of the bins is not configured yet.') . ' ';
847
848   if ($auth->check_right($form->{login}, 'config')) {
849     $msg .= $locale->text('You can create warehouses and bins via the menu "System -> Warehouses".');
850   } else {
851     $msg .= $locale->text('Please ask your administrator to create warehouses and bins.');
852   }
853
854   $form->show_generic_error($msg);
855
856   $lxdebug->leave_sub();
857 }
858
859 sub get_warehouse_idx {
860   my ($warehouse_id) = @_;
861
862   for (my $i = 0; $i < scalar @{$form->{WAREHOUSES}}; $i++) {
863     return $i if ($form->{WAREHOUSES}->[$i]->{id} == $warehouse_id);
864   }
865
866   return -1;
867 }
868
869 sub get_bin_idx {
870   my ($warehouse_index, $bin_id) = @_;
871
872   my $warehouse = $form->{WAREHOUSES}->[$warehouse_index];
873
874   return -1 if (!$warehouse);
875
876   for (my $i = 0; $i < scalar @{ $warehouse->{BINS} }; $i++) {
877     return $i if ($warehouse->{BINS}->[$i]->{id} == $bin_id);
878   }
879
880   return -1;
881 }
882
883 sub update {
884   call_sub($form->{update_nextsub} || $form->{nextsub});
885 }
886
887 sub continue {
888   call_sub($form->{continue_nextsub} || $form->{nextsub});
889 }
890
891 sub stock {
892   call_sub($form->{stock_nextsub} || $form->{nextsub});
893 }
894
895 1;