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