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