Paginierung schneller machen:
[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 transtype_id transtype_ids comment projectnumber);
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 $allrows        = !!($form->{report_generator_output_format} ne 'HTML') ;
597
598   # manual paginating
599   my $pages          = {};
600   my $page           = $::form->{page} || 1;
601   $pages->{per_page} = $::form->{per_page} || 15;
602   my $first_nr       = ($page - 1) * $pages->{per_page};
603   my $last_nr        = $first_nr + $pages->{per_page};
604
605   # no optimisation if qty op
606   if ( !$allrows && $form->{maxrows} && !$filter{qty_op}) {
607     $filter{limit}  = $pages->{per_page};
608     $filter{offset} = ($page - 1) * $pages->{per_page};
609     $first_nr       = 0;
610     $last_nr        = $pages->{per_page};
611   }
612
613   my @contents  = WH->get_warehouse_journal(%filter);
614   # get maxcount
615   if (!$form->{maxrows}) {
616     $form->{maxrows} = scalar @contents ;
617   }
618
619   my $report = SL::ReportGenerator->new(\%myconfig, $form);
620
621   my @hidden_variables = map { "l_${_}" } @columns;
622   push @hidden_variables, qw(warehouse_id bin_id partnumber description chargenumber bestbefore qty_op qty qty_unit unit partunit fromdate todate transtype_ids comment projectnumber);
623   push @hidden_variables, qw(classification_id);
624
625   my %column_defs = (
626     'date'            => { 'text' => $locale->text('Date'), },
627     'trans_id'        => { 'text' => $locale->text('Trans Id'), },
628     'trans_type'      => { 'text' => $locale->text('Trans Type'), },
629     'comment'         => { 'text' => $locale->text('Comment'), },
630     'warehouse_from'  => { 'text' => $locale->text('Warehouse From'), },
631     'warehouse_to'    => { 'text' => $locale->text('Warehouse To'), },
632     'bin_from'        => { 'text' => $locale->text('Bin From'), },
633     'bin_to'          => { 'text' => $locale->text('Bin To'), },
634     'partnumber'      => { 'text' => $locale->text('Part Number'), },
635     'type_and_classific'
636                       => { 'text' => $locale->text('Type'), },
637     'partdescription' => { 'text' => $locale->text('Part Description'), },
638     'chargenumber'    => { 'text' => $locale->text('Charge Number'), },
639     'bestbefore'      => { 'text' => $locale->text('Best Before'), },
640     'qty'             => { 'text' => $locale->text('Qty'), },
641     'unit'            => { 'text' => $locale->text('Part Unit'), },
642     'partunit'        => { 'text' => $locale->text('Unit'), },
643     'employee'        => { 'text' => $locale->text('Employee'), },
644     'projectnumber'   => { 'text' => $locale->text('Project Number'), },
645     'oe_id'           => { 'text' => $locale->text('Document'), },
646   );
647
648   if ($form->{transtype_ids} && 'ARRAY' eq ref $form->{transtype_ids}) {
649     for (my $i = 0; $i < scalar(@{ $form->{transtype_ids} }); $i++) {
650       delete $form->{transtype_ids}[$i] if $form->{transtype_ids}[$i] eq '';
651     }
652     $form->{transtype_ids} = join(",", @{ $form->{transtype_ids} });
653   }
654
655   my $href = build_std_url('action=generate_journal', grep { $form->{$_} } @hidden_variables);
656   $href .= "&maxrows=".$form->{maxrows};
657
658   map { $column_defs{$_}->{link} = $href ."&page=".$page. "&sort=${_}&order=" . Q($_ eq $form->{sort} ? 1 - $form->{order} : $form->{order}) } @columns;
659
660   my %column_alignment = map { $_ => 'right' } qw(qty);
661
662   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
663   $column_defs{partunit}->{visible} = 1;
664   $column_defs{type_and_classific}->{visible} = 1;
665   $column_defs{type_and_classific}->{link} ='';
666
667   $report->set_columns(%column_defs);
668   $report->set_column_order(@columns);
669
670   $report->set_export_options('generate_journal', @hidden_variables, qw(sort order));
671
672   $report->set_sort_indicator($form->{sort}, $form->{order});
673
674   $report->set_options('output_format'        => 'HTML',
675                        'title'                => $form->{title},
676                        'attachment_basename'  => strftime($locale->text('warehouse_journal_list') . '_%Y%m%d', localtime time));
677   $report->set_options_from_form();
678   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
679
680   my $all_units = AM->retrieve_units(\%myconfig, $form);
681
682   my %doc_types = ( 'sales_quotation'         => { script => 'oe', title => $locale->text('Sales quotation') },
683                     'sales_order'             => { script => 'oe', title => $locale->text('Sales Order') },
684                     'request_quotation'       => { script => 'oe', title => $locale->text('Request quotation') },
685                     'purchase_order'          => { script => 'oe', title => $locale->text('Purchase Order') },
686                     'sales_delivery_order'    => { script => 'do', title => $locale->text('Sales delivery order') },
687                     'purchase_delivery_order' => { script => 'do', title => $locale->text('Purchase delivery order') },
688                     'sales_invoice'           => { script => 'is', title => $locale->text('Sales Invoice') },
689                     'purchase_invoice'        => { script => 'ir', title => $locale->text('Purchase Invoice') },
690                   );
691
692   my $idx       = 0;
693
694   foreach my $entry (@contents) {
695     $entry->{type_and_classific} = $::request->presenter->type_abbreviation($entry->{part_type}).
696                                    $::request->presenter->classification_abbreviation($entry->{classification_id});
697     $entry->{qty}        = $form->format_amount(\%myconfig, $entry->{qty});
698     $entry->{trans_type} = $locale->text($entry->{trans_type});
699
700     my $row = { };
701
702     foreach my $column (@columns) {
703       $row->{$column} = {
704         'data'  => $entry->{$column},
705         'align' => $column_alignment{$column},
706       };
707     }
708
709     $row->{trans_type}->{raw_data} = $entry->{trans_type};
710
711     if ($form->{l_oe_id}) {
712       $row->{oe_id}->{data} = '';
713       my $info              = $entry->{oe_id_info};
714
715       if ($info && $info->{id} && $info->{type} && $doc_types{$info->{type}}) {
716         $row->{oe_id} = { data => $doc_types{ $info->{type} }->{title} . ' ' . $info->{number},
717                           link => build_std_url('script=' . $doc_types{ $info->{type} }->{script} . '.pl', 'action=edit', 'id=' . $info->{id}, 'type=' . $info->{type}) };
718       }
719     }
720
721     if ( $allrows || ($idx >= $first_nr && $idx < $last_nr )) {
722       $report->add_data($row);
723     }
724     $idx++;
725   }
726
727   if ( ! $allrows ) {
728       $pages->{max}  = SL::DB::Helper::Paginated::ceil($form->{maxrows}, $pages->{per_page}) || 1;
729       $pages->{page} = $page < 1 ? 1: $page > $pages->{max} ? $pages->{max}: $page;
730       $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{page}, $pages->{max}) } ];
731
732       $report->set_options('raw_bottom_info_text' => $form->parse_html_template('common/paginate',
733                                                             { 'pages' => $pages , 'base_url' => $href.'&sort='.$form->{sort}.'&order='.$form->{order}}) );
734   }
735   $report->generate_with_headers();
736
737   $main::lxdebug->leave_sub();
738 }
739
740 # --------------------------------------------------------------------
741 # Report
742 # --------------------------------------------------------------------
743
744 sub report {
745   $main::lxdebug->enter_sub();
746
747   $main::auth->assert('warehouse_contents | warehouse_management');
748
749   my $form     = $main::form;
750   my %myconfig = %main::myconfig;
751   my $locale   = $main::locale;
752
753   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
754                                      'bins'   => 'BINS', });
755
756   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
757
758   $form->{title}   = $locale->text("Report about warehouse contents");
759
760   $form->header();
761   print $form->parse_html_template("wh/report_filter",
762                                    { "nextsub"    => "generate_report",
763                                      "WAREHOUSES" => $form->{WAREHOUSES},
764                                      "UNITS"      => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
765
766   $main::lxdebug->leave_sub();
767 }
768
769 sub generate_report {
770   $main::lxdebug->enter_sub();
771
772   $main::auth->assert('warehouse_contents | warehouse_management');
773
774   my $form     = $main::form;
775   my %myconfig = %main::myconfig;
776   my $locale   = $main::locale;
777
778   $form->{title}   = $locale->text("Report about warehouse contents");
779   $form->{sort}  ||= 'partnumber';
780   my $sort_col     = $form->{sort};
781
782   my %filter;
783   my @columns = qw(warehousedescription bindescription partnumber type_and_classific partdescription chargenumber bestbefore comment qty partunit  purchase_price stock_value);
784
785   # filter stuff
786   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id classification_id partnumber description chargenumber bestbefore date include_invalid_warehouses);
787
788   # show filter stuff also in report
789   my @options;
790   my $currentdate = $form->current_date(\%myconfig);
791   push @options, $locale->text('Printdate') . " : ".$locale->date(\%myconfig, $currentdate, 1);
792
793   # dispatch all options
794   my $dispatch_options = {
795    warehouse_id   => sub { push @options, $locale->text('Warehouse') . " : " .
796                                             SL::DB::Manager::Warehouse->find_by(id => $form->{warehouse_id})->description},
797    bin_id         => sub { push @options, $locale->text('Bin') . " : " .
798                                             SL::DB::Manager::Bin->find_by(id => $form->{bin_id})->description},
799    partnumber     => sub { push @options, $locale->text('Partnumber')     . " : $form->{partnumber}"},
800    classification_id => sub { push @options, $locale->text('Parts Classification'). " : ".
801                                                SL::DB::Manager::PartClassification->get_first(where => [ id => $form->{classification_id} ] )->description; },
802    description    => sub { push @options, $locale->text('Description')    . " : $form->{description}"},
803    chargenumber   => sub { push @options, $locale->text('Charge Number')  . " : $form->{chargenumber}"},
804    bestbefore     => sub { push @options, $locale->text('Best Before')    . " : $form->{bestbefore}"},
805    include_invalid_warehouses    => sub { push @options, $locale->text('Include invalid warehouses ')},
806   };
807   foreach (keys %filter) {
808    $dispatch_options->{$_}->() if $dispatch_options->{$_};
809   }
810   push @options, $locale->text('Stock Qty for Date') . " " . $locale->date(\%myconfig, $form->{date}?$form->{date}:$currentdate, 1);
811
812   # / end show filter stuff also in report
813
814   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
815   if ($filter{qty_op}) {
816     $form->isblank("qty",      $locale->text('Quantity missing.'));
817     $form->isblank("qty_unit", $locale->text('Unit missing.'));
818
819     $filter{qty}      = $form->{qty};
820     $filter{qty_unit} = $form->{qty_unit};
821   }
822   # /filter stuff
823
824   $form->{report_generator_output_format} = 'HTML' if !$form->{report_generator_output_format};
825
826   # manual paginating
827   my $allrows        = !!($form->{report_generator_output_format} ne 'HTML') ;
828   my $page           = $::form->{page} || 1;
829   my $pages          = {};
830   $pages->{per_page} = $::form->{per_page} || 20;
831   my $first_nr       = ($page - 1) * $pages->{per_page};
832   my $last_nr        = $first_nr + $pages->{per_page};
833
834   # no optimisation if qty op
835   if ( !$allrows && $form->{maxrows} && !$filter{qty_op}) {
836     $filter{limit}  = $pages->{per_page};
837     $filter{offset} = ($page - 1) * $pages->{per_page};
838     $first_nr       = 0;
839     $last_nr        = $pages->{per_page};
840   }
841
842   my @contents  = WH->get_warehouse_report(%filter);
843
844   # get maxcount
845   if (!$form->{maxrows}) {
846     $form->{maxrows} = scalar @contents ;
847   }
848
849   $form->{subtotal} = '' if (!first { $_ eq $sort_col } qw(partnumber partdescription));
850
851   my $report = SL::ReportGenerator->new(\%myconfig, $form);
852
853   my @hidden_variables = map { "l_${_}" } @columns;
854   push @hidden_variables, qw(warehouse_id bin_id partnumber partstypes_id description chargenumber bestbefore qty_op qty qty_unit partunit l_warehousedescription l_bindescription);
855   push @hidden_variables, qw(include_empty_bins subtotal include_invalid_warehouses date);
856   push @hidden_variables, qw(classification_id);
857
858   my %column_defs = (
859     'warehousedescription' => { 'text' => $locale->text('Warehouse'), },
860     'bindescription'       => { 'text' => $locale->text('Bin'), },
861     'partnumber'           => { 'text' => $locale->text('Part Number'), },
862     'type_and_classific'   => { 'text' => $locale->text('Type'), },
863     'partdescription'      => { 'text' => $locale->text('Part Description'), },
864     'chargenumber'         => { 'text' => $locale->text('Charge Number'), },
865     'bestbefore'           => { 'text' => $locale->text('Best Before'), },
866     'qty'                  => { 'text' => $locale->text('Qty'), },
867     'partunit'             => { 'text' => $locale->text('Unit'), },
868     'stock_value'          => { 'text' => $locale->text('Stock value'), },
869     'purchase_price'       => { 'text' => $locale->text('Purchase Price'), },
870   );
871
872   my $href = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
873   $href .= "&maxrows=".$form->{maxrows};
874
875   map { $column_defs{$_}->{link} = $href . "&page=".$page."&sort=${_}&order=" . Q($_ eq $sort_col ? 1 - $form->{order} : $form->{order}) } @columns;
876
877   my %column_alignment = map { $_ => 'right' } qw(qty purchase_price stock_value);
878
879   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
880
881   $column_defs{partunit}->{visible}           = 1;
882   $column_defs{type_and_classific}->{visible} = 1;
883   $column_defs{type_and_classific}->{link} ='';
884
885   $report->set_columns(%column_defs);
886   $report->set_column_order(@columns);
887
888   $report->set_export_options('generate_report', @hidden_variables, qw(sort order));
889
890   $report->set_sort_indicator($sort_col, $form->{order});
891
892   $report->set_options('top_info_text'        => join("\n", @options),
893                        'output_format'        => 'HTML',
894                        'title'                => $form->{title},
895                        'attachment_basename'  => strftime($locale->text('warehouse_report_list') . '_%Y%m%d', localtime time));
896   $report->set_options_from_form();
897   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
898
899   my $all_units = AM->retrieve_units(\%myconfig, $form);
900   my $idx       = 0;
901
902   my @subtotals_columns = qw(qty stock_value);
903   my %subtotals         = map { $_ => 0 } @subtotals_columns;
904
905   my $total_stock_value = 0;
906
907   foreach my $entry (@contents) {
908
909     $entry->{type_and_classific} = $::request->presenter->type_abbreviation($entry->{part_type}).
910                                    $::request->presenter->classification_abbreviation($entry->{classification_id});
911     map { $subtotals{$_} += $entry->{$_} } @subtotals_columns;
912     $total_stock_value   += $entry->{stock_value} * 1;
913     $entry->{qty}         = $form->format_amount(\%myconfig, $entry->{qty});
914 #    $entry->{qty}         = $form->format_amount_units('amount'     => $entry->{qty},
915 #                                                       'part_unit'  => $entry->{partunit},
916 #                                                       'conv_units' => 'convertible');
917     $entry->{stock_value} = $form->format_amount(\%myconfig, $entry->{stock_value} * 1, 2);
918     $entry->{purchase_price} = $form->format_amount(\%myconfig, $entry->{purchase_price} * 1, 2);
919
920     my $row_set = [ { map { $_ => { 'data' => $entry->{$_}, 'align' => $column_alignment{$_} } } @columns } ];
921
922     if ( ($form->{subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
923         && (($idx == (scalar @contents - 1))
924             || ($entry->{$sort_col} ne $contents[$idx + 1]->{$sort_col}))) {
925
926       my $row = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', 'align' => $column_alignment{$_}, } } @columns };
927       $row->{qty}->{data}         = $form->format_amount(\%myconfig, $subtotals{qty});
928 #      $row->{qty}->{data}         = $form->format_amount_units('amount'     => $subtotals{qty} * 1,
929 #                                                               'part_unit'  => $entry->{partunit},
930 #                                                               'conv_units' => 'convertible');
931       $row->{stock_value}->{data} = $form->format_amount(\%myconfig, $subtotals{stock_value} * 1, 2);
932       $row->{purchase_price}->{data} = $form->format_amount(\%myconfig, $subtotals{purchase_price} * 1, 2);
933
934       %subtotals                  = map { $_ => 0 } @subtotals_columns;
935
936       push @{ $row_set }, $row;
937     }
938
939     if ( $allrows || ($idx >= $first_nr && $idx < $last_nr )) {
940         $report->add_data($row_set);
941     }
942     $idx++;
943   }
944
945   if ( $column_defs{stock_value}->{visible} && !$form->{report_generator_csv_options_for_import} ) {
946     $report->add_separator();
947
948     my $row                      = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', } } @columns };
949
950     my $left_col                 = first { $column_defs{$_}->{visible} } @columns;
951
952     $row->{$left_col}->{data}    = $locale->text('Total stock value');
953     $row->{stock_value}->{data}  = $form->format_amount(\%myconfig, $total_stock_value, 2);
954     $row->{stock_value}->{align} = 'right';
955
956     $report->add_data($row);
957   }
958   if ( ! $allrows ) {
959     $pages->{max}  = SL::DB::Helper::Paginated::ceil($form->{maxrows}, $pages->{per_page}) || 1;
960     $pages->{page} = $page < 1 ? 1: $page > $pages->{max} ? $pages->{max}: $page;
961     $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{page}, $pages->{max}) } ];
962
963     $report->set_options('raw_bottom_info_text' => $form->parse_html_template('common/paginate',
964                                                                               {'pages' => $pages , 'base_url' => $href}) );
965   }
966
967   $report->generate_with_headers();
968
969   $main::lxdebug->leave_sub();
970 }
971
972 # --------------------------------------------------------------------
973 # Utility functions
974 # --------------------------------------------------------------------
975
976 sub show_no_warehouses_error {
977   $main::lxdebug->enter_sub();
978
979   my $form     = $main::form;
980   my %myconfig = %main::myconfig;
981   my $locale   = $main::locale;
982
983   my $msg = $locale->text('No warehouse has been created yet or the quantity of the bins is not configured yet.') . ' ';
984
985   if ($main::auth->check_right($::myconfig{login}, 'config')) {
986     $msg .= $locale->text('You can create warehouses and bins via the menu "System -> Warehouses".');
987   } else {
988     $msg .= $locale->text('Please ask your administrator to create warehouses and bins.');
989   }
990
991   $form->show_generic_error($msg);
992
993   $main::lxdebug->leave_sub();
994 }
995
996 sub get_warehouse_idx {
997   my ($warehouse_id) = @_;
998
999   my $form     = $main::form;
1000
1001   for (my $i = 0; $i < scalar @{$form->{WAREHOUSES}}; $i++) {
1002     return $i if ($form->{WAREHOUSES}->[$i]->{id} == $warehouse_id);
1003   }
1004
1005   return -1;
1006 }
1007
1008 sub get_bin_idx {
1009   my ($warehouse_index, $bin_id) = @_;
1010
1011   my $form     = $main::form;
1012
1013   my $warehouse = $form->{WAREHOUSES}->[$warehouse_index];
1014
1015   return -1 if (!$warehouse);
1016
1017   for (my $i = 0; $i < scalar @{ $warehouse->{BINS} }; $i++) {
1018     return $i if ($warehouse->{BINS}->[$i]->{id} == $bin_id);
1019   }
1020
1021   return -1;
1022 }
1023
1024 sub new_item {
1025   $main::lxdebug->enter_sub();
1026   my %params = @_;
1027
1028   my $form     = $main::form;
1029
1030   # change callback
1031   $form->{old_callback} = $form->escape($form->{callback}, 1);
1032   $form->{callback}     = $form->escape("$form->{script}?action=$params{action}", 1);
1033
1034   # save all form variables except action in a previousform variable
1035   my $previousform = join '&', map { my $value = $form->{$_}; $value =~ s/&/%26/; "$_=$value" } grep { !/action/ } keys %$form;
1036   my @HIDDENS = ();
1037
1038 #  push @HIDDENS,      { 'name' => 'previousform', 'value' => $form->escape($previousform, 1) };
1039   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} }, qw(partnumber description unit vc sellprice ean);
1040   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
1041   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{longdescription} };
1042
1043   $form->header();
1044   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
1045
1046   $main::lxdebug->leave_sub();
1047 }
1048
1049 sub update {
1050   my $form     = $main::form;
1051   call_sub($form->{update_nextsub} || $form->{nextsub});
1052 }
1053
1054 sub continue {
1055   my $form     = $main::form;
1056   call_sub($form->{continue_nextsub} || $form->{nextsub});
1057 }
1058
1059 sub stock {
1060   my $form     = $main::form;
1061   call_sub($form->{stock_nextsub} || $form->{nextsub});
1062 }
1063
1064 1;
1065
1066 __END__
1067
1068 =head1 NAME
1069
1070 bin/mozilla/wh.pl - Warehouse frontend.
1071
1072 =head1 FUNCTIONS
1073
1074 =over 4
1075
1076 =item new_item
1077
1078 call new item dialogue from warehouse masks.
1079
1080 PARAMS:
1081   action  => name of sub to be called when new item is done
1082
1083 =back
1084
1085 =cut