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