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