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