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