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