89975cc2a6127f8c332ba0847f3b9db983b293bd
[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
438   if (!$main::show_best_before) {
439       $form->{bestbefore} = '';
440   }
441
442   # 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
443   # Anm. jb 18.3. vielleicht auch nur meine unwissenheit in perl-datenstrukturen
444   my %TRANSFER = (
445     'transfer_type'    => 'assembly',
446     'login'            => $form->{login},
447     'dst_warehouse_id' => $form->{warehouse_id},
448     'dst_bin_id'       => $form->{bin_id},
449     'chargenumber'     => $form->{chargenumber},
450     'bestbefore'       => $form->{bestbefore},
451     'assembly_id'      => $form->{parts_id},
452     'qty'              => $form->{qty},
453     'unit'             => $form->{unit},
454     'comment'          => $form->{comment}
455   );
456
457   my $ret = WH->transfer_assembly (%TRANSFER);
458   # Frage: Ich pack in den return-wert auch gleich die Fehlermeldung. Irgendwelche Nummern als Fehlerkonstanten definieren find ich auch nicht besonders schick...
459   # Ideen? jb 18.3.09
460   if ($ret ne "1"){
461     # 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
462     $form->show_generic_error($ret, 'back_button' => 1);
463   }
464
465   delete @{$form}{qw(parts_id partnumber description qty unit chargenumber bestbefore comment)};
466
467   $form->{saved_message} = $locale->text('The assembly has been created.');
468   $form->{trans_type}    = 'assembly';
469
470   transfer_warehouse_selection();
471
472   $main::lxdebug->leave_sub();
473 }
474
475 sub transfer_stock {
476   $main::lxdebug->enter_sub();
477
478   my $form     = $main::form;
479   my %myconfig = %main::myconfig;
480   my $locale   = $main::locale;
481
482   $form->{qty} = $form->parse_amount(\%myconfig, $form->{qty});
483
484   if ($form->{qty} <= 0) {
485     $form->show_generic_error($locale->text('Invalid quantity.'), 'back_button' => 1);
486   }
487
488   if (!$form->{warehouse_id} || !$form->{bin_id}) {
489     $form->error($locale->text('The warehouse or the bin is missing.'));
490   }
491
492   my $transfer = {
493     'transfer_type'    => 'stock',
494     'dst_warehouse_id' => $form->{warehouse_id},
495     'dst_bin_id'       => $form->{bin_id},
496     'chargenumber'     => $form->{chargenumber},
497     'bestbefore'       => $form->{bestbefore},
498     'parts_id'         => $form->{parts_id},
499     'qty'              => $form->{qty},
500     'unit'             => $form->{unit},
501     'comment'          => $form->{comment},
502   };
503
504   WH->transfer($transfer);
505
506   delete @{$form}{qw(parts_id partnumber description qty unit chargenumber bestbefore comment ean)};
507
508   $form->{saved_message} = $locale->text('The parts have been stocked.');
509   $form->{trans_type}    = 'stock';
510
511   transfer_warehouse_selection();
512
513   $main::lxdebug->leave_sub();
514 }
515
516 # --------------------------------------------------------------------
517 # Transfer: removal
518 # --------------------------------------------------------------------
519
520 sub removal_parts_selection {
521   $main::lxdebug->enter_sub();
522
523   $main::auth->assert('warehouse_management');
524
525   my $form     = $main::form;
526   my %myconfig = %main::myconfig;
527   my $locale   = $main::locale;
528
529   transfer_or_removal_prepare_contents('direction' => 'out');
530
531   $form->{title} = $locale->text('Removal');
532   $form->header();
533   print $form->parse_html_template("wh/removal_parts_selection");
534
535   $main::lxdebug->leave_sub();
536 }
537
538 sub remove_parts {
539   $main::lxdebug->enter_sub();
540
541   $main::auth->assert('warehouse_management');
542
543   my $form     = $main::form;
544   my %myconfig = %main::myconfig;
545   my $locale   = $main::locale;
546
547   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
548                                      'bins'   => 'BINS', });
549
550   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
551   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
552
553   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
554
555   $form->show_generic_error($locale->text("The warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
556
557   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber bestbefore partunit);
558
559   $form->{sort} = 'bindescription';
560   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id});
561   my $all_units = AM->retrieve_units(\%myconfig, $form);
562
563   my @transfers;
564
565   foreach my $row (1 .. $form->{rowcount}) {
566     $form->{"qty_$row"} =~ s/^\s*//;
567     $form->{"qty_$row"} =~ s/\s*$//;
568     next if (!$form->{"qty_$row"});
569
570     my $bin_idx = get_bin_idx($warehouse_idx, $form->{"src_bin_id_$row"});
571     $form->show_generic_error($locale->text("The selected bin does not exist.")) if (-1 == $bin_idx);
572     my $bin     = $warehouse->{BINS}->[$bin_idx];
573
574     my $orig_qty = $form->{"qty_$row"} . " " . $form->{"unit_$row"};
575
576     my $transfer = {
577       'src_warehouse_id' => $form->{warehouse_id},
578       'transfer_type_id' => $form->{transfer_type_id},
579     };
580
581     map { $transfer->{$_} = $form->{"${_}_${row}"} } qw(src_bin_id chargenumber bestbefore parts_id qty);
582
583     my $entry;
584
585     foreach (@contents) {
586       if (($_->{binid} == $transfer->{src_bin_id}) && ($_->{parts_id} == $transfer->{parts_id}) && ($_->{chargenumber} eq $transfer->{chargenumber}) && ($_->{bestbefore} eq $transfer->{bestbefore})) {
587         $entry = $_;
588         last;
589       }
590     }
591
592     if (!$entry) {
593       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
594                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
595     }
596
597     $transfer->{qty}  = $form->parse_amount(\%myconfig, $transfer->{qty}) * $all_units->{$form->{"unit_$row"}}->{factor};
598     $transfer->{qty} /= $all_units->{$entry->{partunit}}->{factor} || 1;
599
600     if (($entry->{qty} < $transfer->{qty}) || (0 >= $transfer->{qty})) {
601       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
602                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
603     }
604
605     $transfer->{comment} = $form->{comment};
606
607     push @transfers, $transfer;
608
609     $entry->{qty} -= $transfer->{qty};
610   }
611
612   if (!scalar @transfers) {
613     $form->show_generic_information($locale->text('Nothing has been selected for removal.'));
614     exit 0;
615   }
616
617   WH->transfer(@transfers);
618
619   $form->{trans_type}    = 'removal';
620   $form->{saved_message} = $locale->text('The parts have been removed.');
621
622   transfer_warehouse_selection();
623
624   $main::lxdebug->leave_sub();
625 }
626
627 # --------------------------------------------------------------------
628 # Journal
629 # --------------------------------------------------------------------
630
631 sub journal {
632   $main::lxdebug->enter_sub();
633
634   $main::auth->assert('warehouse_management');
635
636   my $form     = $main::form;
637   my %myconfig = %main::myconfig;
638
639   $form->get_lists('warehouses' => { 'key'  => 'WAREHOUSES',
640                                      'bins' => 'BINS', });
641
642   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
643
644   $form->{jsscript} = 1;
645
646   $form->header();
647   print $form->parse_html_template("wh/journal_filter", { "UNITS" => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
648
649   $main::lxdebug->leave_sub();
650 }
651
652 sub generate_journal {
653   $main::lxdebug->enter_sub();
654
655   $main::auth->assert('warehouse_management');
656
657   my $form     = $main::form;
658   my %myconfig = %main::myconfig;
659   my $locale   = $main::locale;
660
661   $form->{title}   = $locale->text("WHJournal");
662   $form->{sort}  ||= 'date';
663
664   my %filter;
665   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);
666
667   # filter stuff
668   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id partnumber description chargenumber bestbefore);
669
670   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
671   if ($filter{qty_op}) {
672     $form->isblank("qty",      $locale->text('Quantity missing.'));
673     $form->isblank("qty_unit", $locale->text('Unit missing.'));
674
675     $filter{qty}      = $form->{qty};
676     $filter{qty_unit} = $form->{qty_unit};
677   }
678   # /filter stuff
679
680   my $report = SL::ReportGenerator->new(\%myconfig, $form);
681
682   my @hidden_variables = map { "l_${_}" } @columns;
683   push @hidden_variables, qw(warehouse_id bin_id partnumber description chargenumber bestbefore qty_op qty qty_unit fromdate todate);
684
685   my %column_defs = (
686     'date'            => { 'text' => $locale->text('Date'), },
687     'trans_id'        => { 'text' => $locale->text('Trans Id'), },
688     'trans_type'      => { 'text' => $locale->text('Trans Type'), },
689     'comment'         => { 'text' => $locale->text('Comment'), },
690     'warehouse_from'  => { 'text' => $locale->text('Warehouse From'), },
691     'warehouse_to'    => { 'text' => $locale->text('Warehouse To'), },
692     'bin_from'        => { 'text' => $locale->text('Bin From'), },
693     'bin_to'          => { 'text' => $locale->text('Bin To'), },
694     'partnumber'      => { 'text' => $locale->text('Part Number'), },
695     'partdescription' => { 'text' => $locale->text('Description'), },
696     'chargenumber'    => { 'text' => $locale->text('Charge Number'), },
697     'bestbefore'      => { 'text' => $locale->text('Best Before'), },
698     'qty'             => { 'text' => $locale->text('Qty'), },
699     'employee'        => { 'text' => $locale->text('Employee'), },
700     'projectnumber'   => { 'text' => $locale->text('Project Number'), },
701     'oe_id'           => { 'text' => $locale->text('Document'), },
702   );
703
704   my $href = build_std_url('action=generate_journal', grep { $form->{$_} } @hidden_variables);
705   map { $column_defs{$_}->{link} = $href . "&sort=${_}&order=" . Q($_ eq $form->{sort} ? 1 - $form->{order} : $form->{order}) } @columns;
706
707   my %column_alignment = map { $_ => 'right' } qw(qty);
708
709   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
710
711   $report->set_columns(%column_defs);
712   $report->set_column_order(@columns);
713
714   $report->set_export_options('generate_journal', @hidden_variables, qw(sort order));
715
716   $report->set_sort_indicator($form->{sort}, $form->{order});
717
718   $report->set_options('output_format'        => 'HTML',
719                        'title'                => $form->{title},
720                        'attachment_basename'  => strftime($locale->text('warehouse_journal_list') . '_%Y%m%d', localtime time));
721   $report->set_options_from_form();
722
723   my $all_units = AM->retrieve_units(\%myconfig, $form);
724   my @contents  = WH->get_warehouse_journal(%filter);
725
726   my %doc_types = ( 'sales_quotation'         => { script => 'oe', title => $locale->text('Sales quotation') },
727                     'sales_order'             => { script => 'oe', title => $locale->text('Sales Order') },
728                     'request_quotation'       => { script => 'oe', title => $locale->text('Request quotation') },
729                     'purchase_order'          => { script => 'oe', title => $locale->text('Purchase Order') },
730                     'sales_delivery_order'    => { script => 'do', title => $locale->text('Sales delivery order') },
731                     'purchase_delivery_order' => { script => 'do', title => $locale->text('Purchase delivery order') },
732                     'sales_invoice'           => { script => 'is', title => $locale->text('Sales Invoice') },
733                     'purchase_invoice'        => { script => 'ir', title => $locale->text('Purchase Invoice') },
734                   );
735
736   foreach my $entry (@contents) {
737     $entry->{qty}        = $form->format_amount_units('amount'     => $entry->{qty},
738                                                       'part_unit'  => $entry->{partunit},
739                                                       'conv_units' => 'convertible');
740     $entry->{trans_type} = $locale->text($entry->{trans_type});
741
742     my $row = { };
743
744     foreach my $column (@columns) {
745       $row->{$column} = {
746         'data'  => $entry->{$column},
747         'align' => $column_alignment{$column},
748       };
749     }
750
751     $row->{trans_type}->{raw_data} = $entry->{trans_type};
752
753     if ($form->{l_oe_id}) {
754       $row->{oe_id}->{data} = '';
755       my $info              = $entry->{oe_id_info};
756
757       if ($info && $info->{id} && $info->{type} && $doc_types{$info->{type}}) {
758         $row->{oe_id} = { data => $doc_types{ $info->{type} }->{title} . ' ' . $info->{number},
759                           link => build_std_url('script=' . $doc_types{ $info->{type} }->{script} . '.pl', 'action=edit', 'id=' . $info->{id}, 'type=' . $info->{type}) };
760       }
761     }
762
763     $report->add_data($row);
764   }
765
766   $report->generate_with_headers();
767
768   $main::lxdebug->leave_sub();
769 }
770
771 # --------------------------------------------------------------------
772 # Report
773 # --------------------------------------------------------------------
774
775 sub report {
776   $main::lxdebug->enter_sub();
777
778   $main::auth->assert('warehouse_contents | warehouse_management');
779
780   my $form     = $main::form;
781   my %myconfig = %main::myconfig;
782   my $locale   = $main::locale;
783
784   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
785                                      'bins'   => 'BINS', });
786
787   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
788
789   $form->{jsscript} = 1;
790
791 #  $form->{fokus}   = "partnumber";
792 #  $form->{onload} .= "focus();";
793   $form->{title}   = $locale->text("Report about wareouse contents");
794
795   $form->header();
796   print $form->parse_html_template("wh/report_filter",
797                                    { "nextsub"    => "generate_report",
798                                      "WAREHOUSES" => $form->{WAREHOUSES},
799                                      "UNITS"      => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
800
801   $main::lxdebug->leave_sub();
802 }
803
804 sub generate_report {
805   $main::lxdebug->enter_sub();
806
807   $main::auth->assert('warehouse_contents | warehouse_management');
808
809   my $form     = $main::form;
810   my %myconfig = %main::myconfig;
811   my $locale   = $main::locale;
812
813   $form->{title}   = $locale->text("Report about wareouse contents");
814   $form->{sort}  ||= 'partnumber';
815   my $sort_col     = $form->{sort};
816
817   my %filter;
818   my @columns = qw(warehousedescription bindescription partnumber partdescription chargenumber bestbefore qty stock_value);
819
820   # filter stuff
821   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id partnumber description chargenumber bestbefore);
822
823   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
824   if ($filter{qty_op}) {
825     $form->isblank("qty",      $locale->text('Quantity missing.'));
826     $form->isblank("qty_unit", $locale->text('Unit missing.'));
827
828     $filter{qty}      = $form->{qty};
829     $filter{qty_unit} = $form->{qty_unit};
830   }
831   # /filter stuff
832
833   $form->{subtotal} = '' if (!first { $_ eq $sort_col } qw(partnumber partdescription));
834
835   my $report = SL::ReportGenerator->new(\%myconfig, $form);
836
837   my @hidden_variables = map { "l_${_}" } @columns;
838   push @hidden_variables, qw(warehouse_id bin_id partnumber description chargenumber bestbefore qty_op qty qty_unit l_warehousedescription l_bindescription);
839   push @hidden_variables, qw(include_empty_bins subtotal);
840
841   my %column_defs = (
842     'warehousedescription' => { 'text' => $locale->text('Warehouse'), },
843     'bindescription'       => { 'text' => $locale->text('Bin'), },
844     'partnumber'           => { 'text' => $locale->text('Part Number'), },
845     'partdescription'      => { 'text' => $locale->text('Description'), },
846     'chargenumber'         => { 'text' => $locale->text('Charge Number'), },
847     'bestbefore'           => { 'text' => $locale->text('Best Before'), },
848     'qty'                  => { 'text' => $locale->text('Qty'), },
849     'stock_value'          => { 'text' => $locale->text('Stock value'), },
850   );
851
852   my $href = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
853   map { $column_defs{$_}->{link} = $href . "&sort=${_}&order=" . Q($_ eq $sort_col ? 1 - $form->{order} : $form->{order}) } @columns;
854
855   my %column_alignment = map { $_ => 'right' } qw(qty stock_value);
856
857   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
858
859   $report->set_columns(%column_defs);
860   $report->set_column_order(@columns);
861
862   $report->set_export_options('generate_report', @hidden_variables, qw(sort order));
863
864   $report->set_sort_indicator($sort_col, $form->{order});
865
866   $report->set_options('output_format'        => 'HTML',
867                        'title'                => $form->{title},
868                        'attachment_basename'  => strftime($locale->text('warehouse_report_list') . '_%Y%m%d', localtime time));
869   $report->set_options_from_form();
870
871   my $all_units = AM->retrieve_units(\%myconfig, $form);
872   my @contents  = WH->get_warehouse_report(%filter);
873
874   my $idx       = 0;
875
876   my @subtotals_columns = qw(qty stock_value);
877   my %subtotals         = map { $_ => 0 } @subtotals_columns;
878
879   my $total_stock_value = 0;
880
881   foreach my $entry (@contents) {
882     map { $subtotals{$_} += $entry->{$_} } @subtotals_columns;
883     $total_stock_value   += $entry->{stock_value} * 1;
884
885     $entry->{qty}         = $form->format_amount_units('amount'     => $entry->{qty},
886                                                        'part_unit'  => $entry->{partunit},
887                                                        'conv_units' => 'convertible');
888     $entry->{stock_value} = $form->format_amount(\%myconfig, $entry->{stock_value} * 1, 2);
889
890     my $row_set = [ { map { $_ => { 'data' => $entry->{$_}, 'align' => $column_alignment{$_} } } @columns } ];
891
892     if (($form->{subtotal} eq 'Y')
893         && (($idx == (scalar @contents - 1))
894             || ($entry->{$sort_col} ne $contents[$idx + 1]->{$sort_col}))) {
895
896       my $row = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', 'align' => $column_alignment{$_}, } } @columns };
897       $row->{qty}->{data}         = $form->format_amount_units('amount'     => $subtotals{qty} * 1,
898                                                                'part_unit'  => $entry->{partunit},
899                                                                'conv_units' => 'convertible');
900       $row->{stock_value}->{data} = $form->format_amount(\%myconfig, $subtotals{stock_value} * 1, 2);
901
902       %subtotals                  = map { $_ => 0 } @subtotals_columns;
903
904       push @{ $row_set }, $row;
905     }
906
907     $report->add_data($row_set);
908
909     $idx++;
910   }
911
912   if ($column_defs{stock_value}->{visible}) {
913     $report->add_separator();
914
915     my $row                      = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', } } @columns };
916
917     my $left_col                 = first { $column_defs{$_}->{visible} } @columns;
918
919     $row->{$left_col}->{data}    = $locale->text('Total stock value');
920     $row->{stock_value}->{data}  = $form->format_amount(\%myconfig, $total_stock_value, 2);
921     $row->{stock_value}->{align} = 'right';
922
923     $report->add_data($row);
924   }
925
926   $report->generate_with_headers();
927
928   $main::lxdebug->leave_sub();
929 }
930
931 # --------------------------------------------------------------------
932 # Utility functions
933 # --------------------------------------------------------------------
934
935 sub show_no_warehouses_error {
936   $main::lxdebug->enter_sub();
937
938   my $form     = $main::form;
939   my %myconfig = %main::myconfig;
940   my $locale   = $main::locale;
941
942   my $msg = $locale->text('No warehouse has been created yet or the quantity of the bins is not configured yet.') . ' ';
943
944   if ($main::auth->check_right($form->{login}, 'config')) {
945     $msg .= $locale->text('You can create warehouses and bins via the menu "System -> Warehouses".');
946   } else {
947     $msg .= $locale->text('Please ask your administrator to create warehouses and bins.');
948   }
949
950   $form->show_generic_error($msg);
951
952   $main::lxdebug->leave_sub();
953 }
954
955 sub get_warehouse_idx {
956   my ($warehouse_id) = @_;
957
958   my $form     = $main::form;
959
960   for (my $i = 0; $i < scalar @{$form->{WAREHOUSES}}; $i++) {
961     return $i if ($form->{WAREHOUSES}->[$i]->{id} == $warehouse_id);
962   }
963
964   return -1;
965 }
966
967 sub get_bin_idx {
968   my ($warehouse_index, $bin_id) = @_;
969
970   my $form     = $main::form;
971
972   my $warehouse = $form->{WAREHOUSES}->[$warehouse_index];
973
974   return -1 if (!$warehouse);
975
976   for (my $i = 0; $i < scalar @{ $warehouse->{BINS} }; $i++) {
977     return $i if ($warehouse->{BINS}->[$i]->{id} == $bin_id);
978   }
979
980   return -1;
981 }
982
983 sub new_item {
984   $main::lxdebug->enter_sub();
985   my %params = @_;
986
987   my $form     = $main::form;
988
989   # change callback
990   $form->{old_callback} = $form->escape($form->{callback}, 1);
991   $form->{callback}     = $form->escape("$form->{script}?action=$params{action}", 1);
992
993   # save all form variables except action in a previousform variable
994   my $previousform = join '&', map { my $value = $form->{$_}; $value =~ s/&/%26/; "$_=$value" } grep { !/action/ } keys %$form;
995   my @HIDDENS = ();
996
997 #  push @HIDDENS,      { 'name' => 'previousform', 'value' => $form->escape($previousform, 1) };
998   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} }, qw(partnumber description unit vc sellprice ean);
999   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
1000   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{longdescription} };
1001
1002   $form->header();
1003   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
1004
1005   $main::lxdebug->leave_sub();
1006 }
1007
1008 sub update {
1009   my $form     = $main::form;
1010   call_sub($form->{update_nextsub} || $form->{nextsub});
1011 }
1012
1013 sub continue {
1014   my $form     = $main::form;
1015   call_sub($form->{continue_nextsub} || $form->{nextsub});
1016 }
1017
1018 sub stock {
1019   my $form     = $main::form;
1020   call_sub($form->{stock_nextsub} || $form->{nextsub});
1021 }
1022
1023 1;
1024
1025 __END__
1026
1027 =head1 NAME
1028
1029 bin/mozilla/wh.pl - Warehouse frontend.
1030
1031 =head1 FUNCTIONS
1032
1033 =over 4
1034
1035 =item new_item
1036
1037 call new item dialogue from warehouse masks.
1038
1039 PARAMS:
1040   action  => name of sub to be called when new item is done
1041
1042 =back
1043
1044 =cut