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