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