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