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