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