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