Gefertigte Erzeugnisse wieder zerlegen
[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::CVar;
43 use SL::CT;
44 use SL::Helper::Flash qw(flash_later);
45 use SL::IC;
46 use SL::WH;
47 use SL::OE;
48 # use SL::Helper::Inventory qw(produce_assembly);
49 use SL::Locale::String qw(t8);
50 use SL::ReportGenerator;
51 use SL::Presenter::Tag qw(checkbox_tag);
52 use SL::Presenter::Part;
53
54 use SL::DB::AssemblyInventoryPart;
55 use SL::DB::Part;
56
57 use Data::Dumper;
58
59 require "bin/mozilla/common.pl";
60 require "bin/mozilla/reportgenerator.pl";
61
62 use strict;
63
64 # parserhappy(R):
65
66 # contents of the "transfer_type" table:
67 #  $locale->text('back')
68 #  $locale->text('correction')
69 #  $locale->text('disposed')
70 #  $locale->text('found')
71 #  $locale->text('missing')
72 #  $locale->text('stock')
73 #  $locale->text('shipped')
74 #  $locale->text('transfer')
75 #  $locale->text('used')
76 #  $locale->text('return_material')
77 #  $locale->text('release_material')
78 #  $locale->text('assembled')
79 #  $locale->text('stocktaking')
80
81 # --------------------------------------------------------------------
82 # Transfer
83 # --------------------------------------------------------------------
84
85 sub transfer_warehouse_selection {
86   $main::lxdebug->enter_sub();
87
88   $main::auth->assert('warehouse_management');
89
90   my $form     = $main::form;
91   my %myconfig = %main::myconfig;
92   my $locale   = $main::locale;
93
94   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
95                                      'bins'   => 'BINS', });
96
97   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
98
99   my $units      = AM->retrieve_units(\%myconfig, $form);
100
101   my $part = 0;
102   if ( $form->{parts_id} ) {
103     $part = SL::DB::Part->new();
104     $part->id($form->{parts_id});
105     $part->load();
106   }
107
108   # der zweite Parameter von unit_select_data gibt den default-Namen (selected) vor
109   $form->{UNITS} = AM->unit_select_data($units, $form->{unit}, 0, $part ? $part->unit : 0);
110
111   if (scalar @{ $form->{WAREHOUSES} }) {
112     $form->{warehouse_id} ||= $form->{WAREHOUSES}->[0]->{id};
113     $form->{bin_id}       ||= $form->{WAREHOUSES}->[0]->{BINS}->[0]->{id};
114   }
115
116   my $content;
117
118   if ($form->{trans_type} eq 'removal') {
119     setup_wh_transfer_warehouse_selection_action_bar("removal_parts_selection");
120     $form->{title}   = $locale->text('Removal from Warehouse');
121     $content         = $form->parse_html_template('wh/warehouse_selection');
122
123   } elsif (!$form->{trans_type} || ($form->{trans_type} eq 'transfer')) {
124     setup_wh_transfer_warehouse_selection_action_bar("transfer_parts_selection");
125     $form->{title}   = $locale->text('Transfer');
126     $content         = $form->parse_html_template('wh/warehouse_selection');
127
128   } elsif ($form->{trans_type} eq 'assembly') {
129     setup_wh_transfer_warehouse_selection_assembly_action_bar();
130     $form->{title} = $locale->text('Produce Assembly');
131     $content       = $form->parse_html_template('wh/warehouse_selection_assembly');
132   }
133
134   $form->header();
135   print $content;
136
137   $main::lxdebug->leave_sub();
138 }
139
140 sub transfer_parts_selection {
141   $main::lxdebug->enter_sub();
142
143   $main::auth->assert('warehouse_management');
144
145   my $form     = $main::form;
146   my %myconfig = %main::myconfig;
147   my $locale   = $main::locale;
148
149   transfer_or_removal_prepare_contents('direction' => 'transfer');
150
151   setup_wh_transfer_parts_action_bar();
152
153   $form->{title} = $locale->text('Transfer');
154   $form->header();
155   print $form->parse_html_template("wh/transfer_parts_selection");
156
157   $main::lxdebug->leave_sub();
158 }
159
160 sub transfer_or_removal_prepare_contents {
161   $main::lxdebug->enter_sub();
162
163   $main::auth->assert('warehouse_management');
164
165   my %args = @_;
166
167   my $form     = $main::form;
168   my %myconfig = %main::myconfig;
169   my $locale   = $main::locale;
170
171   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
172                                      'bins'   => 'BINS', });
173
174   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
175   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
176
177   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
178
179   $form->{initial_warehouse_idx} = $warehouse_idx;
180   $form->{warehouse_description} = $warehouse->{description};
181   $warehouse->{selected}         = 1;
182
183   $form->show_generic_error($locale->text("The source warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
184
185   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber bestbefore partunit ean);
186
187   $form->{sort} = 'bindescription';
188   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id},
189                                            "bin_id"       => $form->{bin_id},
190                                            "chargenumber" => $form->{chargenumber},
191                                            "bestbefore"   => $form->{bestbefore},
192                                            "partsid"      => $form->{part_id},
193                                            "ean"          => $form->{ean});
194
195   if (0 == scalar(@contents)) {
196     $form->show_generic_error($locale->text("The selected warehouse is empty, or no stocked items where found that match the filter settings."));
197   }
198
199   my $all_units = AM->retrieve_units(\%myconfig, $form);
200
201   foreach (@contents) {
202     $_->{qty} = $form->format_amount_units('amount'     => $_->{qty},
203                                            'part_unit'  => $_->{partunit},
204                                            'conv_units' => 'convertible');
205     my $this_unit = $_->{partunit};
206
207     if ($all_units->{$_->{partunit}} && ($all_units->{g}->{base_unit} eq $all_units->{$_->{partunit}}->{base_unit})) {
208       $this_unit = "kg";
209     }
210
211     $_->{UNITS} = AM->unit_select_data($all_units, $this_unit, 0, $_->{partunit});
212   }
213
214   my $transfer_types = WH->retrieve_transfer_types($args{direction});
215   map { $_->{description} = $locale->text($_->{description}) } @{ $transfer_types };
216
217   $form->{CONTENTS}       = \@contents;
218   $form->{TRANSFER_TYPES} = $transfer_types;
219
220   $main::lxdebug->leave_sub();
221 }
222
223
224 sub transfer_parts {
225   $main::lxdebug->enter_sub();
226
227   $main::auth->assert('warehouse_management');
228
229   my $form     = $main::form;
230   my %myconfig = %main::myconfig;
231   my $locale   = $main::locale;
232
233   $form->get_lists('warehouses' => { 'key' => 'WAREHOUSES', 'bins' => 'BINS' });
234
235   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
236   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
237
238   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
239
240   $form->show_generic_error($locale->text("The source warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
241
242   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber bestbefore partunit);
243
244   $form->{sort} = 'bindescription';
245   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id});
246   my $all_units = AM->retrieve_units(\%myconfig, $form);
247
248   my @transfers;
249
250   foreach my $row (1 .. $form->{rowcount}) {
251     $form->{"qty_$row"} =~ s/^\s*//;
252     $form->{"qty_$row"} =~ s/\s*$//;
253     next if (!$form->{"qty_$row"});
254
255     my $bin_idx = get_bin_idx($warehouse_idx, $form->{"src_bin_id_$row"});
256     $form->show_generic_error($locale->text("The selected bin does not exist.")) if (-1 == $bin_idx);
257     my $bin     = $warehouse->{BINS}->[$bin_idx];
258
259     my $orig_qty = $form->{"qty_$row"} . " " . $form->{"unit_$row"};
260
261     my $transfer = {
262       'src_warehouse_id' => $form->{warehouse_id},
263       'transfer_type_id' => $form->{transfer_type_id},
264     };
265
266     map { $transfer->{$_} = $form->{"${_}_${row}"} } qw(src_bin_id chargenumber bestbefore parts_id qty dst_warehouse_id dst_bin_id);
267
268     my $entry;
269
270     foreach (@contents) {
271       if (($_->{binid} == $transfer->{src_bin_id}) && ($_->{parts_id} == $transfer->{parts_id}) && ($_->{chargenumber} eq $transfer->{chargenumber}) && $_->{bestbefore} eq $transfer->{bestbefore}) {
272         $entry = $_;
273         last;
274       }
275     }
276
277     if (!$entry) {
278       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
279                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
280     }
281
282     $transfer->{qty}  = $form->parse_amount(\%myconfig, $transfer->{qty}) * $all_units->{$form->{"unit_$row"}}->{factor};
283     $transfer->{qty} /= $all_units->{$entry->{partunit}}->{factor} || 1;
284
285     if (($entry->{qty} < $transfer->{qty}) || (0 >= $transfer->{qty})) {
286       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
287                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
288     }
289
290     $transfer->{comment} = $form->{comment};
291     $transfer->{change_default_bin} = $form->{change_default_bin};
292
293     push @transfers, $transfer;
294
295     $entry->{qty} -= $transfer->{qty};
296   }
297
298   if (!scalar @transfers) {
299     $form->show_generic_information($locale->text('Nothing has been selected for transfer.'));
300     $::dispatcher->end_request;
301   }
302
303   WH->transfer(@transfers);
304
305   $form->{trans_type}    = 'transfer';
306   $form->{saved_message} = $locale->text('The parts have been transferred.');
307
308   transfer_warehouse_selection();
309
310   $main::lxdebug->leave_sub();
311 }
312
313 # --------------------------------------------------------------------
314 # Transfer: stock
315 # --------------------------------------------------------------------
316
317 # --------------------------------------------------------------------
318 # Transfer: assemblies
319 # Dies ist die Auswahlmaske für ein assembly.
320 # Die ist einfach von transfer_assembly_update_part kopiert und nur um den trans_type (assembly) korrigiert worden
321 # Es wäre schön, hier nochmal check_assembly_max_create auf, um die max. Fertigungszahl herauszufinden.
322 # Ich lass das mal als auskommentierte Idee bestehen jb 18.3.09
323 # --------------------------------------------------------------------
324
325 sub transfer_assembly_update_part {
326   my $form     = $main::form;
327   my %myconfig = %main::myconfig;
328   my $locale   = $main::locale;
329
330   $form->{trans_type} = 'assembly';
331   $form->{qty}        = $form->parse_amount(\%myconfig, $form->{qty});
332
333   if (!$form->{parts_id}) {
334     delete $form->{partunit};
335     transfer_warehouse_selection();
336     return;
337
338   }
339
340   my $part = SL::DB::Part->new(id => $::form->{parts_id})->load;
341   @{$form}{qw(parts_id partnumber description)} = ($part->id, $part->partnumber, $part->description);
342
343   transfer_stock_get_partunit();
344   transfer_warehouse_selection();
345 }
346
347 sub transfer_stock_part_selected {
348   $main::lxdebug->enter_sub();
349
350   my $part = shift;
351
352   my $form     = $main::form;
353
354   @{$form}{qw(parts_id partnumber description ean warehouse_id bin_id)} = @{$part}{qw(id partnumber description ean warehouse_id bin_id)};
355
356   transfer_stock_get_partunit();
357   transfer_warehouse_selection();
358
359   $main::lxdebug->leave_sub();
360 }
361
362 sub transfer_stock_get_partunit {
363   $main::lxdebug->enter_sub();
364
365   my $form     = $main::form;
366
367   if ($form->{parts_id}) {
368     my $part_info     = IC->get_basic_part_info('id' => $form->{parts_id});
369     $form->{partunit} = $part_info->{unit};
370   }
371
372   $main::lxdebug->leave_sub();
373 }
374
375 # vorüberlegung jb 22.2.2009
376 # wir benötigen für diese funktion, die anzahl die vom erzeugnis hergestellt werden soll. vielleicht direkt per js fehleingaben verhindern?
377 # ferner dann nochmal mit check_asssembly_max_create gegenprüfen und dann transaktionssicher wegbuchen.
378 # 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
379 # Manko ist derzeit noch, dass unterschiedliche Lagerplätze, bzw. das Quelllager an sich nicht ausgewählt werden können.
380 # Laut Absprache in KW11 09 Ã¼bernimmt mb hier den rest im April ... jb 18.3.09
381
382 sub create_assembly {
383   $main::lxdebug->enter_sub();
384
385   my $form     = $main::form;
386   my %myconfig = %main::myconfig;
387   my $locale   = $main::locale;
388
389   $form->{qty} = $form->parse_amount(\%myconfig, $form->{qty});
390   if ($form->{qty} <= 0) {
391     $form->show_generic_error($locale->text('Invalid quantity.'));
392   }
393   # TODO Es wäre schön, hier schon die maximale Anzahl der zu fertigenden Erzeugnisse zu haben
394   #else { if ($form->{qty} > $maxcreate) { #s.o.
395   #     $form->show_generic_error($locale->text('Can not create that quantity with current stock'));
396   #     $form->show_generic_error('Maximale Stückzahl' . $maxcreate);
397   #   }
398   #  }
399
400   if (!$form->{warehouse_id} || !$form->{bin_id}) {
401     $form->error($locale->text('The warehouse or the bin is missing.'));
402   }
403
404   if (!$::instance_conf->get_show_bestbefore) {
405       $form->{bestbefore} = '';
406   }
407
408   # 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
409   # Anm. jb 18.3. vielleicht auch nur meine unwissenheit in perl-datenstrukturen
410   my %TRANSFER = (
411     'transfer_type'    => 'assembly',
412     'login'            => $::myconfig{login},
413     'dst_warehouse_id' => $form->{warehouse_id},
414     'dst_bin_id'       => $form->{bin_id},
415     'chargenumber'     => $form->{chargenumber},
416     'bestbefore'       => $form->{bestbefore},
417     'assembly_id'      => $form->{parts_id},
418     'qty'              => $form->{qty},
419     'unit'             => $form->{unit},
420     'comment'          => $form->{comment}
421   );
422
423   my $ret = WH->transfer_assembly (%TRANSFER);
424   # Frage: Ich pack in den return-wert auch gleich die Fehlermeldung. Irgendwelche Nummern als Fehlerkonstanten definieren find ich auch nicht besonders schick...
425   # Ideen? jb 18.3.09
426   if ($ret ne "1"){
427     # 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
428     $form->show_generic_error($ret);
429   }
430
431   delete @{$form}{qw(parts_id partnumber description qty unit chargenumber bestbefore comment)};
432
433   $form->{saved_message} = $locale->text('The assembly has been created.');
434   $form->{trans_type}    = 'assembly';
435
436   transfer_warehouse_selection();
437
438   $main::lxdebug->leave_sub();
439 }
440
441 # --------------------------------------------------------------------
442 # Transfer: removal
443 # --------------------------------------------------------------------
444
445 sub removal_parts_selection {
446   $main::lxdebug->enter_sub();
447
448   $main::auth->assert('warehouse_management');
449
450   my $form     = $main::form;
451   my %myconfig = %main::myconfig;
452   my $locale   = $main::locale;
453
454   transfer_or_removal_prepare_contents('direction' => 'out');
455
456   setup_wh_removal_parts_selection_action_bar();
457
458   $form->{title} = $locale->text('Removal');
459   $form->header();
460   print $form->parse_html_template("wh/removal_parts_selection");
461
462   $main::lxdebug->leave_sub();
463 }
464
465 sub remove_parts {
466   $main::lxdebug->enter_sub();
467
468   $main::auth->assert('warehouse_management');
469
470   my $form     = $main::form;
471   my %myconfig = %main::myconfig;
472   my $locale   = $main::locale;
473
474   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
475                                      'bins'   => 'BINS', });
476
477   my $warehouse_idx = get_warehouse_idx($form->{warehouse_id});
478   $form->show_generic_error($locale->text("The selected warehouse does not exist.")) if (-1 == $warehouse_idx);
479
480   my $warehouse = $form->{WAREHOUSES}->[$warehouse_idx];
481
482   $form->show_generic_error($locale->text("The warehouse does not contain any bins.")) if (0 == scalar @{ $warehouse->{BINS} });
483
484   map { $form->{"l_$_"} = 'Y' } qw(parts_id qty warehouseid binid partnumber partdescription bindescription chargenumber bestbefore partunit);
485
486   $form->{sort} = 'bindescription';
487   my @contents  = WH->get_warehouse_report("warehouse_id" => $form->{warehouse_id});
488   my $all_units = AM->retrieve_units(\%myconfig, $form);
489
490   my @transfers;
491
492   foreach my $row (1 .. $form->{rowcount}) {
493     $form->{"qty_$row"} =~ s/^\s*//;
494     $form->{"qty_$row"} =~ s/\s*$//;
495     next if (!$form->{"qty_$row"});
496
497     my $bin_idx = get_bin_idx($warehouse_idx, $form->{"src_bin_id_$row"});
498     $form->show_generic_error($locale->text("The selected bin does not exist.")) if (-1 == $bin_idx);
499     my $bin     = $warehouse->{BINS}->[$bin_idx];
500
501     my $orig_qty = $form->{"qty_$row"} . " " . $form->{"unit_$row"};
502
503     my $transfer = {
504       'src_warehouse_id' => $form->{warehouse_id},
505       'transfer_type_id' => $form->{transfer_type_id},
506     };
507
508     map { $transfer->{$_} = $form->{"${_}_${row}"} } qw(src_bin_id chargenumber bestbefore parts_id qty);
509
510     my $entry;
511
512     foreach (@contents) {
513       if (($_->{binid} == $transfer->{src_bin_id}) && ($_->{parts_id} == $transfer->{parts_id}) && ($_->{chargenumber} eq $transfer->{chargenumber}) && ($_->{bestbefore} eq $transfer->{bestbefore})) {
514         $entry = $_;
515         last;
516       }
517     }
518
519     if (!$entry) {
520       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
521                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
522     }
523
524     $transfer->{qty}  = $form->parse_amount(\%myconfig, $transfer->{qty}) * $all_units->{$form->{"unit_$row"}}->{factor};
525     $transfer->{qty} /= $all_units->{$entry->{partunit}}->{factor} || 1;
526
527     if (($entry->{qty} < $transfer->{qty}) || (0 >= $transfer->{qty})) {
528       $form->error($locale->text("There is not enough left of '#1' in bin '#2' for the removal of #3.",
529                                  $form->{"partdescription_$row"}, $bin->{description}, $orig_qty));
530     }
531
532     $transfer->{comment} = $form->{comment};
533
534     push @transfers, $transfer;
535
536     $entry->{qty} -= $transfer->{qty};
537   }
538
539   if (!scalar @transfers) {
540     $form->show_generic_information($locale->text('Nothing has been selected for removal.'));
541     $::dispatcher->end_request;
542   }
543
544   WH->transfer(@transfers);
545
546   $form->{trans_type}    = 'removal';
547   $form->{saved_message} = $locale->text('The parts have been removed.');
548
549   transfer_warehouse_selection();
550
551   $main::lxdebug->leave_sub();
552 }
553
554 sub disassemble_assembly {
555   $main::lxdebug->enter_sub();
556
557   $main::auth->assert('warehouse_management');
558
559   my $form = $main::form;
560
561   croak("No assembly ids") unless scalar @{ $form->{ids}} > 0;
562
563   # fail safe, only allow disassemble in certain intervals
564   my $undo_date  = DateTime->today->subtract(days => $::instance_conf->get_undo_transfer_interval);
565
566   foreach my $assembly_id (@{ $::form->{ids}} )  {
567     my $assembly_parts;
568     $assembly_parts  = SL::DB::Manager::AssemblyInventoryPart->get_all(where => [ inventory_assembly_id => $assembly_id ]);
569     $form->show_generic_error(t8('No relations found for #1', $assembly_id)) unless $assembly_parts;
570     # check first entry for insertdate
571     # everything in one transaction
572     my $db = SL::DB::Inventory->new->db;
573     $db->with_transaction(sub {
574       my ($assembly_entry, $part_entry);
575       foreach my $assembly_part (@{ $assembly_parts }) {
576         die("No valid entry found") unless (ref($assembly_part)  eq 'SL::DB::AssemblyInventoryPart');
577         # fail safe undo date
578         die("Invalid time interval") unless DateTime->compare($assembly_part->itime, $undo_date);
579
580         $assembly_entry //= $assembly_part->assembly;
581         $part_entry       = $assembly_part->part;
582         $assembly_part->delete;
583         $part_entry->delete;
584       }
585       flash_later('info', t8("Disassembly successful for #1",  $assembly_entry->part->partnumber));
586
587       $assembly_entry->delete;
588
589       1;
590
591     }) || die t8('error while disassembling assembly #1 : #2', $assembly_id)  . $db->error . "\n";
592
593   }
594   $main::lxdebug->leave_sub();
595   $form->redirect;
596 }
597
598 # --------------------------------------------------------------------
599 # Journal
600 # --------------------------------------------------------------------
601
602 sub journal {
603   $main::lxdebug->enter_sub();
604
605   $main::auth->assert('warehouse_management');
606
607   my $form     = $main::form;
608   my %myconfig = %main::myconfig;
609   my $locale   = $main::locale;
610
611   $form->{title} = $locale->text('Report about warehouse transactions');
612   $form->get_lists('warehouses' => { 'key'  => 'WAREHOUSES',
613                                      'bins' => 'BINS', });
614
615   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
616
617   setup_wh_journal_action_bar();
618
619   $form->header();
620   print $form->parse_html_template("wh/journal_filter", { "UNITS" => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)) });
621
622   $main::lxdebug->leave_sub();
623 }
624
625 sub generate_journal {
626   $main::lxdebug->enter_sub();
627
628   $main::auth->assert('warehouse_management');
629
630   my $form     = $main::form;
631   my %myconfig = %main::myconfig;
632   my $locale   = $main::locale;
633
634   setup_wh_journal_list_all_action_bar();
635   $form->{title}   = $locale->text("WHJournal");
636   $form->{sort}  ||= 'date';
637
638   $form->{report_generator_output_format} = 'HTML' if !$form->{report_generator_output_format};
639
640   my %filter;
641   my @columns = qw(ids 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);
642
643   # filter stuff
644   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id classification_id partnumber description chargenumber bestbefore transtype_id transtype_ids comment projectnumber);
645
646   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
647   if ($filter{qty_op}) {
648     $form->isblank("qty",      $locale->text('Quantity missing.'));
649     $form->isblank("qty_unit", $locale->text('Unit missing.'));
650
651     $filter{qty}      = $form->{qty};
652     $filter{qty_unit} = $form->{qty_unit};
653   }
654   # /filter stuff
655
656   my $allrows        = !!($form->{report_generator_output_format} ne 'HTML') ;
657
658   # manual paginating
659   my $pages          = {};
660   my $page           = $::form->{page} || 1;
661   $pages->{per_page} = $::form->{per_page} || 15;
662   my $first_nr       = ($page - 1) * $pages->{per_page};
663   my $last_nr        = $first_nr + $pages->{per_page};
664
665   # no optimisation if qty op
666   if ( !$allrows && $form->{maxrows} && !$filter{qty_op}) {
667     $filter{limit}  = $pages->{per_page};
668     $filter{offset} = ($page - 1) * $pages->{per_page};
669     $first_nr       = 0;
670     $last_nr        = $pages->{per_page};
671   }
672
673   my @contents  = WH->get_warehouse_journal(%filter);
674   # get maxcount
675   if (!$form->{maxrows}) {
676     $form->{maxrows} = scalar @contents ;
677   }
678
679   my $report = SL::ReportGenerator->new(\%myconfig, $form);
680
681   my @hidden_variables = map { "l_${_}" } @columns;
682   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);
683   push @hidden_variables, qw(classification_id);
684
685   my %column_defs = (
686     'ids'             => { raw_header_data => checkbox_tag("", id => "check_all", checkall  => "[data-checkall=1]") },
687     'date'            => { 'text' => $locale->text('Date'), },
688     'trans_id'        => { 'text' => $locale->text('Trans Id'), },
689     'trans_type'      => { 'text' => $locale->text('Trans Type'), },
690     'comment'         => { 'text' => $locale->text('Comment'), },
691     'warehouse_from'  => { 'text' => $locale->text('Warehouse From'), },
692     'warehouse_to'    => { 'text' => $locale->text('Warehouse To'), },
693     'bin_from'        => { 'text' => $locale->text('Bin From'), },
694     'bin_to'          => { 'text' => $locale->text('Bin To'), },
695     'partnumber'      => { 'text' => $locale->text('Part Number'), },
696     'type_and_classific'
697                       => { 'text' => $locale->text('Type'), },
698     'partdescription' => { 'text' => $locale->text('Part Description'), },
699     'chargenumber'    => { 'text' => $locale->text('Charge Number'), },
700     'bestbefore'      => { 'text' => $locale->text('Best Before'), },
701     'qty'             => { 'text' => $locale->text('Qty'), },
702     'unit'            => { 'text' => $locale->text('Part Unit'), },
703     'partunit'        => { 'text' => $locale->text('Unit'), },
704     'employee'        => { 'text' => $locale->text('Employee'), },
705     'projectnumber'   => { 'text' => $locale->text('Project Number'), },
706     'oe_id'           => { 'text' => $locale->text('Document'), },
707   );
708
709   if ($form->{transtype_ids} && 'ARRAY' eq ref $form->{transtype_ids}) {
710     for (my $i = 0; $i < scalar(@{ $form->{transtype_ids} }); $i++) {
711       delete $form->{transtype_ids}[$i] if $form->{transtype_ids}[$i] eq '';
712     }
713     $form->{transtype_ids} = join(",", @{ $form->{transtype_ids} });
714   }
715
716   my $href = build_std_url('action=generate_journal', grep { $form->{$_} } @hidden_variables);
717   $href .= "&maxrows=".$form->{maxrows};
718
719   map { $column_defs{$_}->{link} = $href ."&page=".$page. "&sort=${_}&order=" . Q($_ eq $form->{sort} ? 1 - $form->{order} : $form->{order}) } @columns;
720
721   my %column_alignment = map { $_ => 'right' } qw(qty);
722
723   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
724   $column_defs{partunit}->{visible} = 1;
725   $column_defs{type_and_classific}->{visible} = 1;
726   $column_defs{type_and_classific}->{link} ='';
727   $column_defs{ids}->{visible} = 1;
728
729   $report->set_columns(%column_defs);
730   $report->set_column_order(@columns);
731
732   $report->set_export_options('generate_journal', @hidden_variables, qw(sort order));
733
734   $report->set_sort_indicator($form->{sort}, $form->{order});
735
736   $report->set_options('output_format'        => 'HTML',
737                        'title'                => $form->{title},
738                        'attachment_basename'  => strftime($locale->text('warehouse_journal_list') . '_%Y%m%d', localtime time));
739   $report->set_options_from_form();
740   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
741
742   my $all_units = AM->retrieve_units(\%myconfig, $form);
743
744   my %doc_types = ( 'sales_quotation'         => { script => 'oe', title => $locale->text('Sales quotation') },
745                     'sales_order'             => { script => 'oe', title => $locale->text('Sales Order') },
746                     'request_quotation'       => { script => 'oe', title => $locale->text('Request quotation') },
747                     'purchase_order'          => { script => 'oe', title => $locale->text('Purchase Order') },
748                     'sales_delivery_order'    => { script => 'do', title => $locale->text('Sales delivery order') },
749                     'purchase_delivery_order' => { script => 'do', title => $locale->text('Purchase delivery order') },
750                     'sales_invoice'           => { script => 'is', title => $locale->text('Sales Invoice') },
751                     'purchase_invoice'        => { script => 'ir', title => $locale->text('Purchase Invoice') },
752                   );
753
754   my $idx       = 0;
755
756   foreach my $entry (@contents) {
757     $entry->{type_and_classific} = SL::Presenter::Part::type_abbreviation($entry->{part_type}) .
758                                    SL::Presenter::Part::classification_abbreviation($entry->{classification_id});
759     $entry->{qty}        = $form->format_amount(\%myconfig, $entry->{qty});
760     $entry->{assembled} = $entry->{trans_type} eq 'assembled' ? 1 : '';
761     $entry->{trans_type} = $locale->text($entry->{trans_type});
762     my $row = { };
763
764     foreach my $column (@columns) {
765       $row->{$column} = {
766         'data'  => $entry->{$column},
767         'align' => $column_alignment{$column},
768       };
769     }
770
771     $row->{ids}->{raw_data} = checkbox_tag("ids[]", value => $entry->{id}, "data-checkall" => 1) if $entry->{assembled};
772
773     $row->{trans_type}->{raw_data} = $entry->{trans_type};
774     if ($form->{l_oe_id}) {
775       $row->{oe_id}->{data} = '';
776       my $info              = $entry->{oe_id_info};
777
778       if ($info && $info->{id} && $info->{type} && $doc_types{$info->{type}}) {
779         $row->{oe_id} = { data => $doc_types{ $info->{type} }->{title} . ' ' . $info->{number},
780                           link => build_std_url('script=' . $doc_types{ $info->{type} }->{script} . '.pl', 'action=edit', 'id=' . $info->{id}, 'type=' . $info->{type}) };
781       }
782     }
783
784     if ( $allrows || ($idx >= $first_nr && $idx < $last_nr )) {
785       $report->add_data($row);
786     }
787     $idx++;
788   }
789
790
791     $report->set_options(
792       raw_top_info_text     => $form->parse_html_template('wh/report_top'),
793       raw_bottom_info_text  => $form->parse_html_template('wh/report_bottom', { callback => $href }),
794     );
795   if ( ! $allrows ) {
796       $pages->{max}  = SL::DB::Helper::Paginated::ceil($form->{maxrows}, $pages->{per_page}) || 1;
797       $pages->{page} = $page < 1 ? 1: $page > $pages->{max} ? $pages->{max}: $page;
798       $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{page}, $pages->{max}) } ];
799
800       $report->set_options('raw_bottom_info_text' =>  $form->parse_html_template('wh/report_bottom', { callback => $href }) . $form->parse_html_template('common/paginate',
801                                                             { 'pages' => $pages , 'base_url' => $href.'&sort='.$form->{sort}.'&order='.$form->{order}}) );
802   }
803   $report->generate_with_headers();
804
805   $main::lxdebug->leave_sub();
806 }
807
808 # --------------------------------------------------------------------
809 # Report
810 # --------------------------------------------------------------------
811
812 sub report {
813   $main::lxdebug->enter_sub();
814
815   $main::auth->assert('warehouse_contents | warehouse_management');
816
817   my $form     = $main::form;
818   my %myconfig = %main::myconfig;
819   my $locale   = $main::locale;
820
821   $form->get_lists('warehouses' => { 'key'    => 'WAREHOUSES',
822                                      'bins'   => 'BINS', });
823
824   show_no_warehouses_error() if (!scalar @{ $form->{WAREHOUSES} });
825
826   my $CVAR_CONFIGS = SL::DB::Manager::CustomVariableConfig->get_all_sorted(where => [ module => 'IC' ]);
827   my $INCLUDABLE_CVAR_CONFIGS = [ grep { $_->includeable } @{ $CVAR_CONFIGS } ];
828
829   $form->{title}   = $locale->text("Report about warehouse contents");
830
831   setup_wh_report_action_bar();
832
833   $form->header();
834   print $form->parse_html_template("wh/report_filter",
835                                    { "WAREHOUSES" => $form->{WAREHOUSES},
836                                      "UNITS"      => AM->unit_select_data(AM->retrieve_units(\%myconfig, $form)),
837                                      # "CVAR_CONFIGS"            => $CVAR_CONFIGS, # nyi searchable cvars
838                                      "INCLUDABLE_CVAR_CONFIGS" => $INCLUDABLE_CVAR_CONFIGS,
839                                    });
840
841   $main::lxdebug->leave_sub();
842 }
843
844 sub generate_report {
845   $main::lxdebug->enter_sub();
846
847   $main::auth->assert('warehouse_contents | warehouse_management');
848
849   my $form     = $main::form;
850   my %myconfig = %main::myconfig;
851   my $locale   = $main::locale;
852
853   my $cvar_configs = CVar->get_configs('module' => 'IC');
854
855   $form->{title}   = $locale->text("Report about warehouse contents");
856   $form->{sort}  ||= 'partnumber';
857   my $sort_col     = $form->{sort};
858
859   my %filter;
860   my @columns = qw(warehousedescription bindescription partnumber type_and_classific partdescription chargenumber bestbefore comment qty partunit list_price purchase_price stock_value);
861
862   # filter stuff
863   map { $filter{$_} = $form->{$_} if ($form->{$_}) } qw(warehouse_id bin_id classification_id partnumber description chargenumber bestbefore date include_invalid_warehouses);
864
865   # show filter stuff also in report
866   my @options;
867   my $currentdate = $form->current_date(\%myconfig);
868   push @options, $locale->text('Printdate') . " : ".$locale->date(\%myconfig, $currentdate, 1);
869
870   # dispatch all options
871   my $dispatch_options = {
872    warehouse_id   => sub { push @options, $locale->text('Warehouse') . " : " .
873                                             SL::DB::Manager::Warehouse->find_by(id => $form->{warehouse_id})->description},
874    bin_id         => sub { push @options, $locale->text('Bin') . " : " .
875                                             SL::DB::Manager::Bin->find_by(id => $form->{bin_id})->description},
876    partnumber     => sub { push @options, $locale->text('Partnumber')     . " : $form->{partnumber}"},
877    classification_id => sub { push @options, $locale->text('Parts Classification'). " : ".
878                                                SL::DB::Manager::PartClassification->get_first(where => [ id => $form->{classification_id} ] )->description; },
879    description    => sub { push @options, $locale->text('Description')    . " : $form->{description}"},
880    chargenumber   => sub { push @options, $locale->text('Charge Number')  . " : $form->{chargenumber}"},
881    bestbefore     => sub { push @options, $locale->text('Best Before')    . " : $form->{bestbefore}"},
882    include_invalid_warehouses    => sub { push @options, $locale->text('Include invalid warehouses ')},
883   };
884   foreach (keys %filter) {
885    $dispatch_options->{$_}->() if $dispatch_options->{$_};
886   }
887   push @options, $locale->text('Stock Qty for Date') . " " . $locale->date(\%myconfig, $form->{date}?$form->{date}:$currentdate, 1);
888
889   # / end show filter stuff also in report
890
891   $filter{qty_op} = WH->convert_qty_op($form->{qty_op});
892   if ($filter{qty_op}) {
893     $form->isblank("qty",      $locale->text('Quantity missing.'));
894     $form->isblank("qty_unit", $locale->text('Unit missing.'));
895
896     $filter{qty}      = $form->{qty};
897     $filter{qty_unit} = $form->{qty_unit};
898   }
899   # /filter stuff
900
901   $form->{report_generator_output_format} = 'HTML' if !$form->{report_generator_output_format};
902
903   # manual paginating
904   my $allrows        = $form->{report_generator_output_format} eq 'HTML' ? $form->{allrows} : 1;
905   my $page           = $::form->{page} || 1;
906   my $pages          = {};
907   $pages->{per_page} = $::form->{per_page} || 20;
908   my $first_nr       = ($page - 1) * $pages->{per_page};
909   my $last_nr        = $first_nr + $pages->{per_page};
910
911   # no optimisation if qty op
912   if ( !$allrows && $form->{maxrows} && !$filter{qty_op}) {
913     $filter{limit}  = $pages->{per_page};
914     $filter{offset} = ($page - 1) * $pages->{per_page};
915     $first_nr       = 0;
916     $last_nr        = $pages->{per_page};
917   }
918
919   my @contents  = WH->get_warehouse_report(%filter);
920
921   # get maxcount
922   if (!$form->{maxrows}) {
923     $form->{maxrows} = scalar @contents ;
924   }
925
926   $form->{subtotal} = '' if (!first { $_ eq $sort_col } qw(partnumber partdescription));
927
928   my $report = SL::ReportGenerator->new(\%myconfig, $form);
929
930   my @includeable_custom_variables = grep { $_->{includeable} } @{ $cvar_configs };
931   push @columns, map { "cvar_$_->{name}" } @includeable_custom_variables;
932
933   my @hidden_variables = map { "l_${_}" } @columns;
934   push @hidden_variables, qw(warehouse_id bin_id partnumber partstypes_id description chargenumber bestbefore qty_op qty qty_unit partunit l_warehousedescription l_bindescription);
935   push @hidden_variables, qw(include_empty_bins subtotal include_invalid_warehouses date);
936   push @hidden_variables, qw(classification_id stock_value_basis allrows);
937
938   my %column_defs = (
939     'warehousedescription' => { 'text' => $locale->text('Warehouse'), },
940     'bindescription'       => { 'text' => $locale->text('Bin'), },
941     'partnumber'           => { 'text' => $locale->text('Part Number'), },
942     'type_and_classific'   => { 'text' => $locale->text('Type'), },
943     'partdescription'      => { 'text' => $locale->text('Part Description'), },
944     'chargenumber'         => { 'text' => $locale->text('Charge Number'), },
945     'bestbefore'           => { 'text' => $locale->text('Best Before'), },
946     'qty'                  => { 'text' => $locale->text('Qty'), },
947     'partunit'             => { 'text' => $locale->text('Unit'), },
948     'stock_value'          => { 'text' => $locale->text('Stock value'), },
949     'purchase_price'       => { 'text' => $locale->text('Purchase price'), },
950     'list_price'           => { 'text' => $locale->text('List Price'), },
951   );
952
953   my $href = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
954   $href .= "&maxrows=".$form->{maxrows};
955   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @includeable_custom_variables;
956   %column_defs = (%column_defs, %column_defs_cvars);
957
958   map { $column_defs{$_}->{link} = $href . "&page=".$page."&sort=${_}&order=" . Q($_ eq $sort_col ? 1 - $form->{order} : $form->{order}) } @columns;
959
960   my %column_alignment = map { $_ => 'right' } qw(qty list_price purchase_price stock_value);
961
962   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
963
964   $column_defs{partunit}->{visible}           = 1;
965   $column_defs{type_and_classific}->{visible} = 1;
966   $column_defs{type_and_classific}->{link} ='';
967
968   $report->set_columns(%column_defs);
969   $report->set_column_order(@columns);
970
971   $report->set_export_options('generate_report', @hidden_variables, qw(sort order));
972
973   $report->set_sort_indicator($sort_col, $form->{order});
974
975   $report->set_options('top_info_text'        => join("\n", @options),
976                        'output_format'        => 'HTML',
977                        'title'                => $form->{title},
978                        'attachment_basename'  => strftime($locale->text('warehouse_report_list') . '_%Y%m%d', localtime time));
979   $report->set_options_from_form();
980   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
981   CVar->add_custom_variables_to_report('module'         => 'IC',
982                                        'trans_id_field' => 'parts_id',
983                                        'configs'        => $cvar_configs,
984                                        'column_defs'    => \%column_defs,
985                                        'data'           => \@contents);
986
987   my $all_units = AM->retrieve_units(\%myconfig, $form);
988   my $idx       = 0;
989
990   my @subtotals_columns = qw(qty stock_value);
991   my %subtotals         = map { $_ => 0 } @subtotals_columns;
992
993   my $total_stock_value = 0;
994
995   foreach my $entry (@contents) {
996
997     $entry->{type_and_classific} = SL::Presenter::Part::type_abbreviation($entry->{part_type}).
998                                    SL::Presenter::Part::classification_abbreviation($entry->{classification_id});
999     map { $subtotals{$_} += $entry->{$_} } @subtotals_columns;
1000     $total_stock_value   += $entry->{stock_value} * 1;
1001     $entry->{qty}         = $form->format_amount(\%myconfig, $entry->{qty});
1002 #    $entry->{qty}         = $form->format_amount_units('amount'     => $entry->{qty},
1003 #                                                       'part_unit'  => $entry->{partunit},
1004 #                                                       'conv_units' => 'convertible');
1005     $entry->{stock_value} = $form->format_amount(\%myconfig, $entry->{stock_value} * 1, 2);
1006     $entry->{purchase_price} = $form->format_amount(\%myconfig, $entry->{purchase_price} * 1, 2);
1007     $entry->{list_price}     = $form->format_amount(\%myconfig, $entry->{list_price}     * 1, 2);
1008
1009     my $row_set = [ { map { $_ => { 'data' => $entry->{$_}, 'align' => $column_alignment{$_} } } @columns } ];
1010
1011     if ( ($form->{subtotal} eq 'Y' && !$form->{report_generator_csv_options_for_import} )
1012         && (($idx == (scalar @contents - 1))
1013             || ($entry->{$sort_col} ne $contents[$idx + 1]->{$sort_col}))) {
1014
1015       my $row = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', 'align' => $column_alignment{$_}, } } @columns };
1016       $row->{qty}->{data}         = $form->format_amount(\%myconfig, $subtotals{qty});
1017 #      $row->{qty}->{data}         = $form->format_amount_units('amount'     => $subtotals{qty} * 1,
1018 #                                                               'part_unit'  => $entry->{partunit},
1019 #                                                               'conv_units' => 'convertible');
1020       $row->{stock_value}->{data} = $form->format_amount(\%myconfig, $subtotals{stock_value} * 1, 2);
1021       $row->{purchase_price}->{data} = $form->format_amount(\%myconfig, $subtotals{purchase_price} * 1, 2);
1022       $row->{list_price}->{data}     = $form->format_amount(\%myconfig, $subtotals{list_price}     * 1, 2);
1023
1024       %subtotals                  = map { $_ => 0 } @subtotals_columns;
1025
1026       push @{ $row_set }, $row;
1027     }
1028
1029     if ( $allrows || ($idx >= $first_nr && $idx < $last_nr )) {
1030         $report->add_data($row_set);
1031     }
1032     $idx++;
1033   }
1034
1035   if ( $column_defs{stock_value}->{visible} && !$form->{report_generator_csv_options_for_import} ) {
1036     $report->add_separator();
1037
1038     my $row                      = { map { $_ => { 'data' => '', 'class' => 'listsubtotal', } } @columns };
1039
1040     my $left_col                 = first { $column_defs{$_}->{visible} } @columns;
1041
1042     $row->{$left_col}->{data}    = $locale->text('Total stock value');
1043     $row->{stock_value}->{data}  = $form->format_amount(\%myconfig, $total_stock_value, 2);
1044     $row->{stock_value}->{align} = 'right';
1045
1046     $report->add_data($row);
1047   }
1048   if ( ! $allrows ) {
1049     $pages->{max}  = SL::DB::Helper::Paginated::ceil($form->{maxrows}, $pages->{per_page}) || 1;
1050     $pages->{page} = $page < 1 ? 1: $page > $pages->{max} ? $pages->{max}: $page;
1051     $pages->{common} = [ grep { $_->{visible} } @{ SL::DB::Helper::Paginated::make_common_pages($pages->{page}, $pages->{max}) } ];
1052
1053     $report->set_options('raw_bottom_info_text' => $form->parse_html_template('common/paginate',
1054                                                                               {'pages' => $pages , 'base_url' => $href}) );
1055   }
1056
1057   $report->generate_with_headers();
1058
1059   $main::lxdebug->leave_sub();
1060 }
1061
1062 # --------------------------------------------------------------------
1063 # Utility functions
1064 # --------------------------------------------------------------------
1065
1066 sub show_no_warehouses_error {
1067   $main::lxdebug->enter_sub();
1068
1069   my $form     = $main::form;
1070   my %myconfig = %main::myconfig;
1071   my $locale   = $main::locale;
1072
1073   my $msg = $locale->text('No warehouse has been created yet or the quantity of the bins is not configured yet.') . ' ';
1074
1075   if ($main::auth->check_right($::myconfig{login}, 'config')) {
1076     $msg .= $locale->text('You can create warehouses and bins via the menu "System -> Warehouses".');
1077   } else {
1078     $msg .= $locale->text('Please ask your administrator to create warehouses and bins.');
1079   }
1080
1081   $form->show_generic_error($msg);
1082
1083   $main::lxdebug->leave_sub();
1084 }
1085
1086 sub get_warehouse_idx {
1087   my ($warehouse_id) = @_;
1088
1089   my $form     = $main::form;
1090
1091   for (my $i = 0; $i < scalar @{$form->{WAREHOUSES}}; $i++) {
1092     return $i if ($form->{WAREHOUSES}->[$i]->{id} == $warehouse_id);
1093   }
1094
1095   return -1;
1096 }
1097
1098 sub get_bin_idx {
1099   my ($warehouse_index, $bin_id) = @_;
1100
1101   my $form     = $main::form;
1102
1103   my $warehouse = $form->{WAREHOUSES}->[$warehouse_index];
1104
1105   return -1 if (!$warehouse);
1106
1107   for (my $i = 0; $i < scalar @{ $warehouse->{BINS} }; $i++) {
1108     return $i if ($warehouse->{BINS}->[$i]->{id} == $bin_id);
1109   }
1110
1111   return -1;
1112 }
1113
1114 sub new_item {
1115   $main::lxdebug->enter_sub();
1116   my %params = @_;
1117
1118   my $form     = $main::form;
1119
1120   # change callback
1121   $form->{old_callback} = $form->escape($form->{callback}, 1);
1122   $form->{callback}     = $form->escape("$form->{script}?action=$params{action}", 1);
1123
1124   # save all form variables except action in a previousform variable
1125   my $previousform = join '&', map { my $value = $form->{$_}; $value =~ s/&/%26/; "$_=$value" } grep { !/action/ } keys %$form;
1126   my @HIDDENS = ();
1127
1128 #  push @HIDDENS,      { 'name' => 'previousform', 'value' => $form->escape($previousform, 1) };
1129   push @HIDDENS, map +{ 'name' => $_,             'value' => $form->{$_} }, qw(partnumber description unit vc sellprice ean);
1130   push @HIDDENS,      { 'name' => 'taxaccount2',  'value' => $form->{taxaccounts} };
1131   push @HIDDENS,      { 'name' => 'notes',        'value' => $form->{longdescription} };
1132
1133   $form->header();
1134   print $form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
1135
1136   $main::lxdebug->leave_sub();
1137 }
1138
1139 sub update {
1140   my $form     = $main::form;
1141   call_sub($form->{update_nextsub} || $form->{nextsub});
1142 }
1143
1144 sub continue {
1145   my $form     = $main::form;
1146   call_sub($form->{continue_nextsub} || $form->{nextsub});
1147 }
1148
1149 sub stock {
1150   my $form     = $main::form;
1151   call_sub($form->{stock_nextsub} || $form->{nextsub});
1152 }
1153
1154 sub setup_wh_transfer_warehouse_selection_action_bar {
1155   my ($action) = @_;
1156
1157   for my $bar ($::request->layout->get('actionbar')) {
1158     $bar->add(
1159       action => [
1160         t8('Update'),
1161         submit    => [ '#form', { action => $action } ],
1162         accesskey => 'enter',
1163       ],
1164     );
1165   }
1166 }
1167
1168 sub setup_wh_transfer_warehouse_selection_assembly_action_bar {
1169   my ($action) = @_;
1170
1171   for my $bar ($::request->layout->get('actionbar')) {
1172     $bar->add(
1173       action => [
1174         t8('Update'),
1175         submit    => [ '#form', { action => 'transfer_assembly_update_part' } ],
1176         accesskey => 'enter',
1177       ],
1178       action => [
1179         t8('Produce'),
1180         submit   => [ '#form', { action => 'create_assembly' } ],
1181         disabled => $::form->{parts_id} ? undef : $::locale->text('No assembly has been selected yet.'),
1182       ],
1183     );
1184   }
1185 }
1186
1187 sub setup_wh_transfer_parts_action_bar {
1188   my ($action) = @_;
1189
1190   for my $bar ($::request->layout->get('actionbar')) {
1191     $bar->add(
1192       action => [
1193         t8('Transfer'),
1194         submit    => [ '#form', { action => 'transfer_parts' } ],
1195         accesskey => 'enter',
1196       ],
1197       action => [
1198         t8('Back'),
1199         call => [ 'kivi.history_back' ],
1200       ],
1201     );
1202   }
1203 }
1204
1205 sub setup_wh_removal_parts_selection_action_bar {
1206   my ($action) = @_;
1207
1208   for my $bar ($::request->layout->get('actionbar')) {
1209     $bar->add(
1210       action => [
1211         t8('Transfer out'),
1212         submit    => [ '#form', { action => 'remove_parts' } ],
1213         accesskey => 'enter',
1214       ],
1215       action => [
1216         t8('Back'),
1217         call => [ 'kivi.history_back' ],
1218       ],
1219     );
1220   }
1221 }
1222
1223 sub setup_wh_report_action_bar {
1224   my ($action) = @_;
1225
1226   for my $bar ($::request->layout->get('actionbar')) {
1227     $bar->add(
1228       action => [
1229         t8('Show'),
1230         submit    => [ '#form', { action => 'generate_report' } ],
1231         accesskey => 'enter',
1232       ],
1233     );
1234   }
1235 }
1236
1237 sub setup_wh_journal_action_bar {
1238   my ($action) = @_;
1239
1240   for my $bar ($::request->layout->get('actionbar')) {
1241     $bar->add(
1242       action => [
1243         t8('Show'),
1244         submit    => [ '#form', { action => 'generate_journal' } ],
1245         accesskey => 'enter',
1246       ],
1247     );
1248   }
1249 }
1250 sub setup_wh_journal_list_all_action_bar {
1251   my ($action) = @_;
1252   for my $bar ($::request->layout->get('actionbar')) {
1253     $bar->add(
1254       combobox => [
1255         action => [ t8('Actions') ],
1256         action => [
1257           t8('Disassemble Assembly'),
1258             submit => [ '#form', { action => 'disassemble_assembly' } ],
1259             checks => [ [ 'kivi.check_if_entries_selected', '[name="ids[]"]' ] ],
1260           ],
1261         ],
1262     );
1263   }
1264 }
1265
1266
1267 1;
1268
1269 __END__
1270
1271 =head1 NAME
1272
1273 bin/mozilla/wh.pl - Warehouse frontend.
1274
1275 =head1 FUNCTIONS
1276
1277 =over 4
1278
1279 =item new_item
1280
1281 call new item dialogue from warehouse masks.
1282
1283 PARAMS:
1284   action  => name of sub to be called when new item is done
1285
1286 =back
1287
1288 =cut