Erzeugnisse fertigen, erste Version fertiggestellt. Bugzilla noch oeffnen fuer rueckv...
[kivitendo-erp.git] / SL / WH.pm
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 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1999-2003
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 #  Warehouse module
32 #
33 #======================================================================
34
35 package WH;
36
37 use SL::AM;
38 use SL::DBUtils;
39 use SL::Form;
40 use warnings;
41 #use strict;
42 sub transfer {
43   $main::lxdebug->enter_sub();
44
45   my $self = shift;
46
47   if (!@_) {
48     $main::lxdebug->leave_sub();
49     return;
50   }
51
52   my $myconfig = \%main::myconfig;
53   my $form     = $main::form;
54
55   my $dbh      = $form->get_standard_dbh($myconfig);
56
57   my $units    = AM->retrieve_units($myconfig, $form);
58
59   my $query    = qq|SELECT * FROM transfer_type|;
60   my $sth      = prepare_execute_query($form, $dbh, $query);
61
62   my %transfer_types;
63
64   while (my $ref = $sth->fetchrow_hashref()) {
65     $transfer_types{$ref->{direction}} ||= { };
66     $transfer_types{$ref->{direction}}->{$ref->{description}} = $ref->{id};
67   }
68
69   my @part_ids  = map { $_->{parts_id} } @_;
70   my %partunits = selectall_as_map($form, $dbh, qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids ) . qq|)|, 'id', 'unit', @part_ids);
71
72   my ($now)     = selectrow_query($form, $dbh, qq|SELECT current_date|);
73
74   $query = qq|INSERT INTO inventory (warehouse_id, bin_id, parts_id, chargenumber, oe_id, orderitems_id, shippingdate,
75                                      employee_id, project_id, trans_id, trans_type_id, comment, qty)
76               VALUES (?, ?, ?, ?, ?, ?, ?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?, ?, ?)|;
77
78   $sth   = prepare_query($form, $dbh, $query);
79
80   my @directions = (undef, 'out', 'in', 'transfer');
81
82   while (@_) {
83     my $transfer   = shift;
84     my ($trans_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
85
86     my ($direction, @values) = (0);
87
88     $direction |= 1 if ($transfer->{src_warehouse_id} && $transfer->{src_bin_id});
89     $direction |= 2 if ($transfer->{dst_warehouse_id} && $transfer->{dst_bin_id});
90
91     push @values, conv_i($transfer->{parts_id}), "$transfer->{chargenumber}", conv_i($transfer->{oe_id}), conv_i($transfer->{orderitems_id});
92     push @values, $transfer->{shippingdate} eq 'current_date' ? $now : conv_date($transfer->{shippingdate}), $form->{login}, conv_i($transfer->{project_id}), $trans_id;
93
94     if ($transfer->{transfer_type_id}) {
95       push @values, $transfer->{transfer_type_id};
96     } else {
97       push @values, $transfer_types{$directions[$direction]}->{$transfer->{transfer_type}};
98     }
99
100     push @values, "$transfer->{comment}";
101
102     my $qty = $transfer->{qty};
103
104     if ($transfer->{unit}) {
105       my $partunit = $partunits{$transfer->{parts_id}};
106
107       $qty *= $units->{$transfer->{unit}}->{factor};
108       $qty /= $units->{$partunit}->{factor} || 1 if ($partunit);
109     }
110
111     if ($direction & 1) {
112       do_statement($form, $sth, $query, conv_i($transfer->{src_warehouse_id}), conv_i($transfer->{src_bin_id}), @values, $qty * -1);
113     }
114
115     if ($direction & 2) {
116       do_statement($form, $sth, $query, conv_i($transfer->{dst_warehouse_id}), conv_i($transfer->{dst_bin_id}), @values, $qty);
117     }
118   }
119
120   $sth->finish();
121
122   $dbh->commit();
123
124   $main::lxdebug->leave_sub();
125 }
126 #
127 #       Testfall:
128 #
129
130 sub transfer_assembly {
131   $main::lxdebug->enter_sub();
132
133   my $self     = shift;
134   my %params   = @_;
135   Common::check_params(\%params, qw(assembly_id dst_warehouse_id login qty unit dst_bin_id chargenumber comment));
136
137 #  my $maxcreate=WH->check_assembly_max_create(assembly_id =>$params{'assembly_id'}, dbh => $my_dbh);
138
139   my $myconfig = \%main::myconfig;
140   my $form     = $main::form;
141   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
142
143
144 # Ablauferklärung
145 #
146 # ... Standard-Check oben Ende. Hier die eigentliche SQL-Abfrage
147 # select parts_id,qty from assembly where id=1064;
148
149
150   my $query    = qq|select parts_id,qty from assembly where id = ?|;
151   my $sth_part_qty_assembly      = prepare_execute_query($form, $dbh, $query, $params{assembly_id});
152
153 # Hier wird das prepared Statement für die Schleife über alle Lagerplätze vorbereitet
154   my $transferPartSQL = qq|INSERT INTO inventory (parts_id, warehouse_id, bin_id, chargenumber, comment, employee_id, qty, trans_id, trans_type_id)
155                             VALUES (?, ?, ?, ?, ?,(SELECT id FROM employee WHERE login = ?), ?, nextval('id'), 
156                                     (SELECT id FROM transfer_type WHERE direction = 'out' AND description = 'used'))|;
157   my $sthTransferPartSQL   = prepare_query($form, $dbh, $transferPartSQL);
158
159   my $kannNichtFertigen ="";    # der return-string für die fehlermeldung inkl. welche waren zum fertigen noch fehlen
160
161   while (my $hash_ref = $sth_part_qty_assembly->fetchrow_hashref()) {   # Schleife für $query=select parts_id,qty from assembly 
162
163     my $partsQTY = $hash_ref->{qty} * $params{qty}; # benötigte teile * anzahl erzeugnisse
164     my $currentPart_ID = $hash_ref->{parts_id};
165
166     # Überprüfen, ob diese Anzahl gefertigt werden kann
167     my $max_parts = get_max_qty_parts($self, parts_id => $currentPart_ID, warehouse_id => $params{dst_warehouse_id}); #$self angeben, damit die Standardkonvention (Name, Parameter) eingehalten wird
168
169     if ($partsQTY  > $max_parts){
170
171       # Gibt es hier ein Problem mit nicht "escapten" Zeichen?
172         $kannNichtFertigen .= "Zum Fertigen fehlen:" . abs($partsQTY) . " Stueck der Ware:" . get_part_description($self, parts_id => $currentPart_ID) . ", um das Erzeugnis herzustellen. <br>";       # Konnte die Menge nicht mit der aktuellen Anzahl der Waren fertigen
173     }
174
175 # Eine kurze Vorabfrage, um den Lagerplatz und die Chargennummber zu bestimmen
176 # Offen: Die Summe über alle Lagerplätze wird noch nicht gebildet
177 # Gelöst: Wir haben vorher schon die Abfrage durchgeführt, ob wir fertigen können.
178 # Noch besser gelöst: Wir laufen durch alle benötigten Waren zum Fertigen und geben eine Rückmeldung an den Benutzer was noch fehlt
179 # und lösen den Rest dann so wie bei xplace im Barcode-Programm
180 # S.a. Kommentar im bin/mozilla-Code mb übernimmt und macht das in ordentlich
181
182     my $tempquery =     qq|SELECT SUM(qty), bin_id, chargenumber   FROM inventory  WHERE warehouse_id = ? AND parts_id = ?  GROUP BY bin_id, chargenumber having SUM(qty)>0|;
183     my $tempsth   =     prepare_execute_query($form, $dbh, $tempquery, $params{dst_warehouse_id}, $currentPart_ID);
184
185     # Alle Werte zu dem einzelnen Artikel, die wir später auslagern
186     my $tmpPartsQTY = $partsQTY;
187
188     while (my $temphash_ref = $tempsth->fetchrow_hashref()) {
189       my $temppart_bin_id       = $temphash_ref->{bin_id}; # kann man hier den quelllagerplatz beim verbauen angeben?
190       my $temppart_chargenumber = $temphash_ref->{chargenumber};
191       my $temppart_qty  = $temphash_ref->{sum};
192       if ($tmpPartsQTY > $temppart_qty) {       # wir haben noch mehr waren zum wegbuchen. Wir buchen den kompletten Lagerplatzbestand und zählen die Hilfsvariable runter
193         $tmpPartsQTY = $tmpPartsQTY - $temppart_qty;
194         $temppart_qty = $temppart_qty * -1;     # beim analyiseren des sql-trace, war dieser wert positiv, wenn * -1 als berechnung in der parameter-übergabe angegeben wird. Dieser Wert IST und BLEIBT positiv!! Hilfe. Liegt das daran, dass dieser Wert aus einem SQL-Statement stammt?
195         do_statement($form, $sthTransferPartSQL, $transferPartSQL, $currentPart_ID, $params{dst_warehouse_id}, $temppart_bin_id, $temppart_chargenumber, 'Verbraucht für ' . get_part_description($self, parts_id => $params{assembly_id}), $params{login}, $temppart_qty);
196
197         # hier ist noch ein fehler am besten mit definierten erzeugnissen debuggen 02/2009 jb
198         # idee: ausbuch algorithmus mit rekursion lösen und an- und abschaltbar machen
199         # das problem könnte sein, dass strict nicht an war und sth global eine andere zuweisung bekam
200         # auf jeden fall war der internal-server-error nach aktivierung von strict und warnings plus ein paar my-definitionen weg
201       } else {  # okay, wir haben weniger oder gleich Waren die wir wegbuchen müssen, wir können also aufhören
202         $tmpPartsQTY *=-1;
203         do_statement($form, $sthTransferPartSQL, $transferPartSQL, $currentPart_ID, $params{dst_warehouse_id}, $temppart_bin_id, $temppart_chargenumber, 'Verbraucht für ' . get_part_description($self, parts_id => $params{assembly_id}), $params{login}, $tmpPartsQTY);
204         last;   # beendet die schleife (springt zum letzten element)
205       }
206     }   # ende while SELECT SUM(qty), bin_id, chargenumber   FROM inventory  WHERE warehouse_id
207   } #ende while select parts_id,qty from assembly where id = ?
208   if ($kannNichtFertigen) {
209     return $kannNichtFertigen;
210   }
211
212   # soweit alles gut. Jetzt noch die wirkliche Lagerbewegung für das Erzeugnis ausführen ... 
213   my $transferAssemblySQL = qq|INSERT INTO inventory (parts_id, warehouse_id, bin_id, chargenumber, comment, employee_id, qty, trans_id, trans_type_id)
214                             VALUES (?, ?, ?, ?, ?, (SELECT id FROM employee WHERE login = ?), ?, nextval('id'), 
215                                     (SELECT id FROM transfer_type WHERE direction = 'in' AND description = 'stock'))|;
216   my $sthTransferAssemblySQL   = prepare_query($form, $dbh, $transferAssemblySQL);
217   do_statement($form, $sthTransferAssemblySQL, $transferAssemblySQL, $params{assembly_id}, $params{dst_warehouse_id}, $params{dst_bin_id}, $params{chargenumber}, $params{comment}, $params{login}, $params{qty});
218   $dbh->commit();
219
220   $main::lxdebug->leave_sub();
221   return 1;     # Alles erfolgreich
222 }
223
224 sub get_warehouse_journal {
225   $main::lxdebug->enter_sub();
226
227   my $self      = shift;
228   my %filter    = @_;
229
230   my $myconfig  = \%main::myconfig;
231   my $form      = $main::form;
232
233   my $all_units = AM->retrieve_units($myconfig, $form);
234
235   # connect to database
236   my $dbh = $form->get_standard_dbh($myconfig);
237
238   # filters
239   my (@filter_ary, @filter_vars, $joins);
240
241   if ($filter{warehouse_id} ne '') {
242     push @filter_ary, "w1.id = ? OR w2.id = ?";
243     push @filter_vars, $filter{warehouse_id}, $filter{warehouse_id};
244   }
245
246   if ($filter{bin_id} ne '') {
247     push @filter_ary, "b1.id = ? OR b2.id = ?";
248     push @filter_vars, $filter{bin_id}, $filter{bin_id};
249   }
250
251   if ($filter{partnumber}) {
252     push @filter_ary, "p.partnumber ILIKE ?";
253     push @filter_vars, '%' . $filter{partnumber} . '%';
254   }
255
256   if ($filter{description}) {
257     push @filter_ary, "(p.description ILIKE ?)";
258     push @filter_vars, '%' . $filter{description} . '%';
259   }
260
261   if ($filter{chargenumber}) {
262     push @filter_ary, "i1.chargenumber ILIKE ?";
263     push @filter_vars, '%' . $filter{chargenumber} . '%';
264   }
265
266   if ($form->{fromdate}) {
267     push @filter_ary, "?::DATE <= i1.itime::DATE";
268     push @filter_vars, $form->{fromdate};
269   }
270
271   if ($form->{todate}) {
272     push @filter_ary, "?::DATE >= i1.itime::DATE";
273     push @filter_vars, $form->{todate};
274   }
275
276   if ($form->{l_employee}) {
277     $joins .= "";
278   }
279
280   # prepare qty comparison for later filtering
281   my ($f_qty_op, $f_qty, $f_qty_base_unit);
282   if ($filter{qty_op} && defined($filter{qty}) && $filter{qty_unit} && $all_units->{$filter{qty_unit}}) {
283     $f_qty_op        = $filter{qty_op};
284     $f_qty           = $filter{qty} * $all_units->{$filter{qty_unit}}->{factor};
285     $f_qty_base_unit = $all_units->{$filter{qty_unit}}->{base_unit};
286   }
287
288   map { $_ = "(${_})"; } @filter_ary;
289
290   # if of a property number or description is requested,
291   # automatically check the matching id too.
292   map { $form->{"l_${_}id"} = "Y" if ($form->{"l_${_}description"} || $form->{"l_${_}number"}); } qw(warehouse bin);
293
294   # customize shown entry for not available fields.
295   $filter{na} = '-' unless $filter{na};
296
297   # make order, search in $filter and $form
298   $form->{sort}   = $filter{sort}             unless $form->{sort};
299   $form->{order}  = ($form->{sort} = 'itime') unless $form->{sort};
300   $form->{sort}   = 'itime'                   if     $form->{sort} eq "date";
301   $form->{order}  = $filter{order}            unless $form->{order};
302   $form->{sort}  .= (($form->{order}) ? " DESC" : " ASC");
303
304   my $where_clause = join(" AND ", @filter_ary) . " AND " if (@filter_ary);
305
306   $select_tokens{'trans'} = {
307      "parts_id"             => "i1.parts_id",
308      "qty"                  => "ABS(SUM(i1.qty))",
309      "partnumber"           => "p.partnumber",
310      "partdescription"      => "p.description",
311      "bindescription"       => "b.description",
312      "chargenumber"         => "i1.chargenumber",
313      "warehousedescription" => "w.description",
314      "partunit"             => "p.unit",
315      "bin_from"             => "b1.description",
316      "bin_to"               => "b2.description",
317      "warehouse_from"       => "w1.description",
318      "warehouse_to"         => "w2.description",
319      "comment"              => "i1.comment",
320      "trans_type"           => "tt.description",
321      "trans_id"             => "i1.trans_id",
322      "date"                 => "i1.itime::DATE",
323      "itime"                => "i1.itime",
324      "employee"             => "e.name",
325      "projectnumber"        => "COALESCE(pr.projectnumber, '$filter{na}')",
326      };
327
328   $select_tokens{'out'} = {
329      "bin_to"               => "'$filter{na}'",
330      "warehouse_to"         => "'$filter{na}'",
331      };
332
333   $select_tokens{'in'} = {
334      "bin_from"             => "'$filter{na}'",
335      "warehouse_from"       => "'$filter{na}'",
336      };
337
338   # build the select clauses.
339   # take all the requested ones from the first hash and overwrite them from the out/in hashes if present.
340   for my $i ('trans', 'out', 'in') {
341     $select{$i} = join ', ', map { +/^l_/; ($select_tokens{$i}{"$'"} || $select_tokens{'trans'}{"$'"}) . " AS r_$'" }
342           ( grep( { !/qty$/ and /^l_/ and $form->{$_} eq 'Y' } keys %$form), qw(l_parts_id l_qty l_partunit l_itime) );
343   }
344
345   my $group_clause = join ", ", map { +/^l_/; "r_$'" }
346         ( grep( { !/qty$/ and /^l_/ and $form->{$_} eq 'Y' } keys %$form), qw(l_parts_id l_partunit l_itime) );
347
348   my $query =
349   qq|SELECT DISTINCT $select{trans}
350     FROM inventory i1
351     LEFT JOIN inventory i2 ON i1.trans_id = i2.trans_id
352     LEFT JOIN parts p ON i1.parts_id = p.id
353     LEFT JOIN bin b1 ON i1.bin_id = b1.id
354     LEFT JOIN bin b2 ON i2.bin_id = b2.id
355     LEFT JOIN warehouse w1 ON i1.warehouse_id = w1.id
356     LEFT JOIN warehouse w2 ON i2.warehouse_id = w2.id
357     LEFT JOIN transfer_type tt ON i1.trans_type_id = tt.id
358     LEFT JOIN project pr ON i1.project_id = pr.id
359     LEFT JOIN employee e ON i1.employee_id = e.id
360     WHERE $where_clause i2.qty = -i1.qty AND i2.qty > 0 AND
361           i1.trans_id IN ( SELECT i.trans_id FROM inventory i GROUP BY i.trans_id HAVING COUNT(i.trans_id) = 2 )
362     GROUP BY $group_clause
363
364     UNION
365
366     SELECT DISTINCT $select{out}
367     FROM inventory i1
368     LEFT JOIN inventory i2 ON i1.trans_id = i2.trans_id
369     LEFT JOIN parts p ON i1.parts_id = p.id
370     LEFT JOIN bin b1 ON i1.bin_id = b1.id
371     LEFT JOIN bin b2 ON i2.bin_id = b2.id
372     LEFT JOIN warehouse w1 ON i1.warehouse_id = w1.id
373     LEFT JOIN warehouse w2 ON i2.warehouse_id = w2.id
374     LEFT JOIN transfer_type tt ON i1.trans_type_id = tt.id
375     LEFT JOIN project pr ON i1.project_id = pr.id
376     LEFT JOIN employee e ON i1.employee_id = e.id
377     WHERE $where_clause i1.qty < 0 AND
378           i1.trans_id IN ( SELECT i.trans_id FROM inventory i GROUP BY i.trans_id HAVING COUNT(i.trans_id) = 1 )
379     GROUP BY $group_clause
380
381     UNION
382
383     SELECT DISTINCT $select{in}
384     FROM inventory i1
385     LEFT JOIN inventory i2 ON i1.trans_id = i2.trans_id
386     LEFT JOIN parts p ON i1.parts_id = p.id
387     LEFT JOIN bin b1 ON i1.bin_id = b1.id
388     LEFT JOIN bin b2 ON i2.bin_id = b2.id
389     LEFT JOIN warehouse w1 ON i1.warehouse_id = w1.id
390     LEFT JOIN warehouse w2 ON i2.warehouse_id = w2.id
391     LEFT JOIN transfer_type tt ON i1.trans_type_id = tt.id
392     LEFT JOIN project pr ON i1.project_id = pr.id
393     LEFT JOIN employee e ON i1.employee_id = e.id
394     WHERE $where_clause i1.qty > 0 AND
395           i1.trans_id IN ( SELECT i.trans_id FROM inventory i GROUP BY i.trans_id HAVING COUNT(i.trans_id) = 1 )
396     GROUP BY $group_clause
397     ORDER BY r_$form->{sort}|;
398
399   my $sth = prepare_execute_query($form, $dbh, $query, @filter_vars, @filter_vars, @filter_vars);
400
401   my @contents = ();
402   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
403     map { /^r_/; $ref->{"$'"} = $ref->{$_} } keys %$ref;
404     my $qty = $ref->{"qty"} * 1;
405
406     next unless ($qty > 0);
407
408     if ($f_qty_op) {
409       my $part_unit = $all_units->{$ref->{"partunit"}};
410       next unless ($part_unit && ($part_unit->{"base_unit"} eq $f_qty_base_unit));
411       $qty *= $part_unit->{"factor"};
412       next if (('=' eq $f_qty_op) && ($qty != $f_qty));
413       next if (('>=' eq $f_qty_op) && ($qty < $f_qty));
414       next if (('<=' eq $f_qty_op) && ($qty > $f_qty));
415     }
416
417     push @contents, $ref;
418   }
419
420   $sth->finish();
421
422   $main::lxdebug->leave_sub();
423
424   return @contents;
425 }
426
427 #
428 # This sub is the primary function to retrieve information about items in warehouses.
429 # $filter is a hashref and supports the following keys:
430 #  - warehouse_id - will return matches with this warehouse_id only
431 #  - partnumber   - will return only matches where the given string is a substring of the partnumber
432 #  - partsid      - will return matches with this parts_id only
433 #  - description  - will return only matches where the given string is a substring of the description
434 #  - chargenumber - will return only matches where the given string is a substring of the chargenumber
435 #  - charge_ids   - must be an arrayref. will return contents with these ids only
436 #  - expires_in   - will only return matches that expire within the given number of days
437 #                   will also add a column named 'has_expired' containing if the match has already expired or not
438 #  - hazardous    - will return matches with the flag hazardous only
439 #  - oil          - will return matches with the flag oil only
440 #  - qty, qty_op  - quantity filter (more info to come)
441 #  - sort, order_by - sorting (more to come)
442 #  - reservation  - will provide an extra column containing the amount reserved of this match
443 # note: reservation flag turns off warehouse_* or bin_* information. both together don't make sense, since reserved info is stored separately
444 #
445 sub get_warehouse_report {
446   $main::lxdebug->enter_sub();
447
448   my $self      = shift;
449   my %filter    = @_;
450
451   my $myconfig  = \%main::myconfig;
452   my $form      = $main::form;
453
454   my $all_units = AM->retrieve_units($myconfig, $form);
455
456   # connect to database
457   my $dbh = $form->get_standard_dbh($myconfig);
458
459   # filters
460   my (@filter_ary, @filter_vars, @wh_bin_filter_ary, @wh_bin_filter_vars, $columns, $group_by);
461
462   delete $form->{include_empty_bins} unless ($form->{l_warehousedescription} || $form->{l_bindescription});
463
464   if ($filter{warehouse_id}) {
465     push @wh_bin_filter_ary,  "w.id = ?";
466     push @wh_bin_filter_vars, $filter{warehouse_id};
467   }
468
469   if ($filter{bin_id}) {
470     push @wh_bin_filter_ary,  "b.id = ?";
471     push @wh_bin_filter_vars, $filter{bin_id};
472   }
473
474   push @filter_ary,  @wh_bin_filter_ary;
475   push @filter_vars, @wh_bin_filter_vars;
476
477   if ($filter{partnumber}) {
478     push @filter_ary,  "p.partnumber ILIKE ?";
479     push @filter_vars, '%' . $filter{partnumber} . '%';
480   }
481
482   if ($filter{description}) {
483     push @filter_ary,  "p.description ILIKE ?";
484     push @filter_vars, '%' . $filter{description} . '%';
485   }
486
487   if ($filter{partsid}) {
488     push @filter_ary,  "p.id = ?";
489     push @filter_vars, $filter{partsid};
490   }
491
492   if ($filter{chargenumber}) {
493     push @filter_ary,  "i.chargenumber ILIKE ?";
494     push @filter_vars, '%' . $filter{chargenumber} . '%';
495   }
496
497   # prepare qty comparison for later filtering
498   my ($f_qty_op, $f_qty, $f_qty_base_unit);
499
500   if ($filter{qty_op} && defined $filter{qty} && $filter{qty_unit} && $all_units->{$filter{qty_unit}}) {
501     $f_qty_op        = $filter{qty_op};
502     $f_qty           = $filter{qty} * $all_units->{$filter{qty_unit}}->{factor};
503     $f_qty_base_unit = $all_units->{$filter{qty_unit}}->{base_unit};
504   }
505
506   map { $_ = "(${_})"; } @filter_ary;
507
508   # if of a property number or description is requested,
509   # automatically check the matching id too.
510   map { $form->{"l_${_}id"} = "Y" if ($form->{"l_${_}description"} || $form->{"l_${_}number"}); } qw(warehouse bin);
511
512   # make order, search in $filter and $form
513   $form->{sort}  =  $filter{sort}  unless $form->{sort};
514   $form->{sort}  =  "parts_id"     unless $form->{sort};
515   $form->{order} =  $filter{order} unless $form->{order};
516   $form->{sort}  =~ s/ASC|DESC//; # kill stuff left in from previous queries
517   my $orderby    =  $form->{sort};
518   $form->{sort} .=  (($form->{order}) ? " DESC" : " ASC");
519
520   my $where_clause = join " AND ", ("1=1", @filter_ary);
521
522   my %select_tokens = (
523      "parts_id"              => "i.parts_id",
524      "qty"                  => "SUM(i.qty)",
525      "warehouseid"          => "i.warehouse_id",
526      "partnumber"           => "p.partnumber",
527      "partdescription"      => "p.description",
528      "bindescription"       => "b.description",
529      "binid"                => "b.id",
530      "chargenumber"         => "i.chargenumber",
531      "chargeid"             => "c.id",
532      "warehousedescription" => "w.description",
533      "partunit"             => "p.unit",
534      "stock_value"          => "p.lastcost / COALESCE(pfac.factor, 1)",
535   );
536   my $select_clause = join ', ', map { +/^l_/; "$select_tokens{$'} AS $'" }
537         ( grep( { !/qty/ and /^l_/ and $form->{$_} eq 'Y' } keys %$form),
538           qw(l_parts_id l_qty l_partunit) );
539
540   my $group_clause = join ", ", map { +/^l_/; "$'" }
541         ( grep( { !/qty/ and /^l_/ and $form->{$_} eq 'Y' } keys %$form),
542           qw(l_parts_id l_partunit) );
543
544   my %join_tokens = (
545     "stock_value" => "LEFT JOIN price_factors pfac ON (p.price_factor_id = pfac.id)",
546     );
547
548   my $joins = join ' ', grep { $_ } map { +/^l_/; $join_tokens{"$'"} }
549         ( grep( { !/qty/ and /^l_/ and $form->{$_} eq 'Y' } keys %$form),
550           qw(l_parts_id l_qty l_partunit) );
551
552   my $query =
553     qq|SELECT $select_clause
554       $columns
555       FROM inventory i
556       LEFT JOIN parts     p ON i.parts_id     = p.id
557       LEFT JOIN bin       b ON i.bin_id       = b.id
558       LEFT JOIN warehouse w ON i.warehouse_id = w.id
559       $joins
560       WHERE $where_clause
561       GROUP BY $group_clause $group_by
562       ORDER BY $form->{sort}|;
563
564   my $sth = prepare_execute_query($form, $dbh, $query, @filter_vars);
565
566   my (%non_empty_bins, @all_fields, @contents);
567
568   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
569     $ref->{qty} *= 1;
570     my $qty      = $ref->{qty};
571
572     next unless ($qty != 0);
573
574     if ($f_qty_op) {
575       my $part_unit = $all_units->{$ref->{partunit}};
576       next if (!$part_unit || ($part_unit->{base_unit} ne $f_qty_base_unit));
577       $qty *= $part_unit->{factor};
578       next if (('='  eq $f_qty_op) && ($qty != $f_qty));
579       next if (('>=' eq $f_qty_op) && ($qty <  $f_qty));
580       next if (('<=' eq $f_qty_op) && ($qty >  $f_qty));
581     }
582
583     if ($form->{include_empty_bins}) {
584       $non_empty_bins{$ref->{binid}} = 1;
585       @all_fields                    = keys %{ $ref } unless (@all_fields);
586     }
587
588     $ref->{stock_value} *= $ref->{qty};
589
590     push @contents, $ref;
591   }
592
593   $sth->finish();
594
595   if ($form->{include_empty_bins}) {
596     $query =
597       qq|SELECT
598            w.id AS warehouseid, w.description AS warehousedescription,
599            b.id AS binid, b.description AS bindescription
600          FROM bin b
601          LEFT JOIN warehouse w ON (b.warehouse_id = w.id)|;
602
603     @filter_ary  = @wh_bin_filter_ary;
604     @filter_vars = @wh_bin_filter_vars;
605
606     my @non_empty_bin_ids = keys %non_empty_bins;
607     if (@non_empty_bin_ids) {
608       push @filter_ary,  qq|NOT b.id IN (| . join(', ', map { '?' } @non_empty_bin_ids) . qq|)|;
609       push @filter_vars, @non_empty_bin_ids;
610     }
611
612     $query .= qq| WHERE | . join(' AND ', map { "($_)" } @filter_ary) if (@filter_ary);
613
614     $sth    = prepare_execute_query($form, $dbh, $query, @filter_vars);
615
616     while (my $ref = $sth->fetchrow_hashref()) {
617       map { $ref->{$_} ||= "" } @all_fields;
618       push @contents, $ref;
619     }
620     $sth->finish();
621
622     if (grep { $orderby eq $_ } qw(bindescription warehousedescription)) {
623       @contents = sort { ($a->{$orderby} cmp $b->{$orderby}) * (($form->{order}) ? 1 : -1) } @contents;
624     }
625   }
626
627   $main::lxdebug->leave_sub();
628
629   return @contents;
630 }
631
632 sub convert_qty_op {
633   $main::lxdebug->enter_sub();
634
635   my ($self, $qty_op) = @_;
636
637   if (!$qty_op || ($qty_op eq "dontcare")) {
638     $main::lxdebug->leave_sub();
639     return undef;
640   }
641
642   if ($qty_op eq "atleast") {
643     $qty_op = '>=';
644   } elsif ($qty_op eq "atmost") {
645     $qty_op = '<=';
646   } else {
647     $qty_op = '=';
648   }
649
650   $main::lxdebug->leave_sub();
651
652   return $qty_op;
653 }
654
655 sub retrieve_transfer_types {
656   $main::lxdebug->enter_sub();
657
658   my $self      = shift;
659   my $direction = shift;
660
661   my $myconfig  = \%main::myconfig;
662   my $form      = $main::form;
663
664   my $dbh       = $form->get_standard_dbh($myconfig);
665
666   my $types     = selectall_hashref_query($form, $dbh, qq|SELECT * FROM transfer_type WHERE direction = ? ORDER BY sortkey|, $direction);
667
668   $main::lxdebug->leave_sub();
669
670   return $types;
671 }
672
673 sub get_basic_bin_info {
674   $main::lxdebug->enter_sub();
675
676   my $self     = shift;
677   my %params   = @_;
678
679   Common::check_params(\%params, qw(id));
680
681   my $myconfig = \%main::myconfig;
682   my $form     = $main::form;
683
684   my $dbh      = $params{dbh} || $form->get_standard_dbh();
685
686   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
687
688   my $query    =
689     qq|SELECT b.id AS bin_id, b.description AS bin_description,
690          w.id AS warehouse_id, w.description AS warehouse_description
691        FROM bin b
692        LEFT JOIN warehouse w ON (b.warehouse_id = w.id)
693        WHERE b.id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
694
695   my $result = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
696
697   if ('' eq ref $params{id}) {
698     $result = $result->[0] || { };
699     $main::lxdebug->leave_sub();
700
701     return $result;
702   }
703
704   $main::lxdebug->leave_sub();
705
706   return map { $_->{bin_id} => $_ } @{ $result };
707 }
708 #
709 # Eingabe:      Teilenummer, Lagernummer (warehouse)
710 # Ausgabe:      Die maximale Anzahl der Teile in diesem Lager
711 #
712 sub get_max_qty_parts {
713 $main::lxdebug->enter_sub();
714
715   my $self     = shift;
716   my %params   = @_;
717
718   Common::check_params(\%params, qw(parts_id warehouse_id)); #die brauchen wir 
719
720   my $myconfig = \%main::myconfig;
721   my $form     = $main::form;
722
723   my $dbh      = $params{dbh} || $form->get_standard_dbh();
724
725   my $query = qq| SELECT SUM(qty), bin_id, chargenumber  FROM inventory where parts_id = ? AND warehouse_id = ? GROUP BY bin_id, chargenumber|;
726
727   my $sth_QTY      = prepare_execute_query($form, $dbh, $query, ,$params{parts_id}, $params{warehouse_id}); #info: aufruf an DBUtils.pm
728   
729   my $max_qty_parts = 0; #Initialisierung mit 0
730   while (my $ref = $sth_QTY->fetchrow_hashref()) {      # wir laufen über alle chargen und Lagerorte (s.a. SQL-Query oben)
731     $max_qty_parts += $ref->{sum};      
732   }
733
734   $main::lxdebug->leave_sub();
735
736   return $max_qty_parts;
737 }
738
739 #
740 # Eingabe:      Teilenummer, Lagernummer (warehouse)
741 # Ausgabe:      Die Beschreibung der Ware bzw. Erzeugnis
742 #
743 sub get_part_description {
744 $main::lxdebug->enter_sub();
745
746   my $self     = shift;
747   my %params   = @_;
748
749   Common::check_params(\%params, qw(parts_id )); #die brauchen wir 
750
751   my $myconfig = \%main::myconfig;
752   my $form     = $main::form;
753
754   my $dbh      = $params{dbh} || $form->get_standard_dbh();
755
756   my $query = qq| SELECT partnumber, description FROM parts where id = ? |;
757
758   my $sth      = prepare_execute_query($form, $dbh, $query, ,$params{parts_id}); #info: aufruf zu DBUtils.pm
759   
760   my $ref = $sth->fetchrow_hashref(); 
761   my $part_description = $ref->{partnumber} . " " . $ref->{description};        
762
763   $main::lxdebug->leave_sub();
764
765   return $part_description;
766 }
767
768
769 1;