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