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