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