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