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