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