delivery_order_items_stock persistent machen Teil 2
[kivitendo-erp.git] / SL / DO.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 # Delivery Order entry module
32 #======================================================================
33
34 package DO;
35
36 use List::Util qw(max);
37 use YAML;
38
39 use SL::AM;
40 use SL::Common;
41 use SL::CVar;
42 use SL::DB::DeliveryOrder;
43 use SL::DB::Status;
44 use SL::DBUtils;
45 use SL::HTML::Restrict;
46 use SL::RecordLinks;
47 use SL::IC;
48 use SL::TransNumber;
49
50 use strict;
51
52 sub transactions {
53   $main::lxdebug->enter_sub();
54
55   my ($self)   = @_;
56
57   my $myconfig = \%main::myconfig;
58   my $form     = $main::form;
59
60   # connect to database
61   my $dbh = $form->get_standard_dbh($myconfig);
62
63   my (@where, @values, $where);
64
65   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
66
67   my $query =
68     qq|SELECT dord.id, dord.donumber, dord.ordnumber, dord.cusordnumber,
69          dord.transdate, dord.reqdate,
70          ct.${vc}number, ct.name, dord.${vc}_id, dord.globalproject_id,
71          dord.closed, dord.delivered, dord.shippingpoint, dord.shipvia,
72          dord.transaction_description,
73          pr.projectnumber AS globalprojectnumber,
74          dep.description AS department,
75          e.name AS employee,
76          sm.name AS salesman
77        FROM delivery_orders dord
78        LEFT JOIN $vc ct ON (dord.${vc}_id = ct.id)
79        LEFT JOIN contacts cp ON (dord.cp_id = cp.cp_id)
80        LEFT JOIN employee e ON (dord.employee_id = e.id)
81        LEFT JOIN employee sm ON (dord.salesman_id = sm.id)
82        LEFT JOIN project pr ON (dord.globalproject_id = pr.id)
83        LEFT JOIN department dep ON (dord.department_id = dep.id)
84 |;
85
86   push @where, ($form->{type} eq 'sales_delivery_order' ? '' : 'NOT ') . qq|COALESCE(dord.is_sales, FALSE)|;
87
88   if ($form->{department_id}) {
89     push @where,  qq|dord.department_id = ?|;
90     push @values, conv_i($form->{department_id});
91   }
92
93   if ($form->{project_id}) {
94     push @where,
95       qq|(dord.globalproject_id = ?) OR EXISTS
96           (SELECT * FROM delivery_order_items doi
97            WHERE (doi.project_id = ?) AND (doi.delivery_order_id = dord.id))|;
98     push @values, conv_i($form->{project_id}), conv_i($form->{project_id});
99   }
100
101   if ($form->{"${vc}_id"}) {
102     push @where,  qq|dord.${vc}_id = ?|;
103     push @values, $form->{"${vc}_id"};
104
105   } elsif ($form->{$vc}) {
106     push @where,  qq|ct.name ILIKE ?|;
107     push @values, '%' . $form->{$vc} . '%';
108   }
109
110   if ($form->{"cp_name"}) {
111     push @where, "(cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
112     push @values, ('%' . $form->{"cp_name"} . '%')x2;
113   }
114
115   foreach my $item (qw(employee_id salesman_id)) {
116     next unless ($form->{$item});
117     push @where, "dord.$item = ?";
118     push @values, conv_i($form->{$item});
119   }
120   if (!$main::auth->assert('sales_all_edit', 1)) {
121     push @where, qq|dord.employee_id = (select id from employee where login= ?)|;
122     push @values, $form->{login};
123   }
124
125   foreach my $item (qw(donumber ordnumber cusordnumber transaction_description)) {
126     next unless ($form->{$item});
127     push @where,  qq|dord.$item ILIKE ?|;
128     push @values, '%' . $form->{$item} . '%';
129   }
130
131   if (($form->{open} || $form->{closed}) &&
132       ($form->{open} ne $form->{closed})) {
133     push @where, ($form->{open} ? "NOT " : "") . "COALESCE(dord.closed, FALSE)";
134   }
135
136   if (($form->{notdelivered} || $form->{delivered}) &&
137       ($form->{notdelivered} ne $form->{delivered})) {
138     push @where, ($form->{delivered} ? "" : "NOT ") . "COALESCE(dord.delivered, FALSE)";
139   }
140
141   if ($form->{serialnumber}) {
142     push @where, 'dord.id IN (SELECT doi.delivery_order_id FROM delivery_order_items doi WHERE doi.serialnumber LIKE ?)';
143     push @values, '%' . $form->{serialnumber} . '%';
144   }
145
146   if($form->{transdatefrom}) {
147     push @where,  qq|dord.transdate >= ?|;
148     push @values, conv_date($form->{transdatefrom});
149   }
150
151   if($form->{transdateto}) {
152     push @where,  qq|dord.transdate <= ?|;
153     push @values, conv_date($form->{transdateto});
154   }
155
156   if($form->{reqdatefrom}) {
157     push @where,  qq|dord.reqdate >= ?|;
158     push @values, conv_date($form->{reqdatefrom});
159   }
160
161   if($form->{reqdateto}) {
162     push @where,  qq|dord.reqdate <= ?|;
163     push @values, conv_date($form->{reqdateto});
164   }
165
166   if (@where) {
167     $query .= " WHERE " . join(" AND ", map { "($_)" } @where);
168   }
169
170   my %allowed_sort_columns = (
171     "transdate"               => "dord.transdate",
172     "reqdate"                 => "dord.reqdate",
173     "id"                      => "dord.id",
174     "donumber"                => "dord.donumber",
175     "ordnumber"               => "dord.ordnumber",
176     "name"                    => "ct.name",
177     "employee"                => "e.name",
178     "salesman"                => "sm.name",
179     "shipvia"                 => "dord.shipvia",
180     "transaction_description" => "dord.transaction_description",
181     "department"              => "lower(dep.description)",
182   );
183
184   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
185   my $sortorder = "dord.id";
186   if ($form->{sort} && grep($form->{sort}, keys(%allowed_sort_columns))) {
187     $sortorder = $allowed_sort_columns{$form->{sort}};
188   }
189
190   $query .= qq| ORDER by | . $sortorder . " $sortdir";
191
192   $form->{DO} = selectall_hashref_query($form, $dbh, $query, @values);
193
194   if (scalar @{ $form->{DO} }) {
195     $query =
196       qq|SELECT id
197          FROM oe
198          WHERE NOT COALESCE(quotation, FALSE)
199            AND (ordnumber = ?)
200            AND (COALESCE(${vc}_id, 0) != 0)|;
201
202     my $sth = prepare_query($form, $dbh, $query);
203
204     foreach my $dord (@{ $form->{DO} }) {
205       next unless ($dord->{ordnumber});
206       do_statement($form, $sth, $query, $dord->{ordnumber});
207       ($dord->{oe_id}) = $sth->fetchrow_array();
208     }
209
210     $sth->finish();
211   }
212
213   $main::lxdebug->leave_sub();
214 }
215
216 sub save {
217   $main::lxdebug->enter_sub();
218
219   my ($self)   = @_;
220
221   my $myconfig = \%main::myconfig;
222   my $form     = $main::form;
223
224   # connect to database, turn off autocommit
225   my $dbh = $form->get_standard_dbh($myconfig);
226   my $restricter = SL::HTML::Restrict->create;
227
228   my ($query, @values, $sth, $null);
229
230   my $all_units = AM->retrieve_units($myconfig, $form);
231   $form->{all_units} = $all_units;
232
233   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
234                                           dbh    => $dbh);
235
236   my $trans_number     = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{donumber}, id => $form->{id});
237   $form->{donumber}  ||= $trans_number->create_unique;
238   $form->{employee_id} = (split /--/, $form->{employee})[1] if !$form->{employee_id};
239   $form->get_employee($dbh) unless ($form->{employee_id});
240
241   my $ml = ($form->{type} eq 'sales_delivery_order') ? 1 : -1;
242
243   my (@processed_doi, @processed_dois);
244
245   if ($form->{id}) {
246
247     # only delete shipto complete
248     $query = qq|DELETE FROM shipto WHERE trans_id = ? AND module = 'DO'|;
249     do_query($form, $dbh, $query, conv_i($form->{id}));
250
251   } else {
252
253     $query = qq|SELECT nextval('id')|;
254     ($form->{id}) = selectrow_query($form, $dbh, $query);
255
256     $query = qq|INSERT INTO delivery_orders (id, donumber, employee_id, currency_id, taxzone_id) VALUES (?, '', ?, (SELECT currency_id FROM defaults LIMIT 1), ?)|;
257     do_query($form, $dbh, $query, $form->{id}, conv_i($form->{employee_id}), $form->{taxzone_id});
258   }
259
260   my $project_id;
261   my $items_reqdate;
262
263   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
264   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
265   my $price_factor;
266
267   my %part_id_map = map { $_ => 1 } grep { $_ } map { $form->{"id_$_"} } (1 .. $form->{rowcount});
268   my @part_ids    = keys %part_id_map;
269   my %part_unit_map;
270
271   if (@part_ids) {
272     $query         = qq|SELECT id, unit FROM parts WHERE id IN (| . join(', ', map { '?' } @part_ids) . qq|)|;
273     %part_unit_map = selectall_as_map($form, $dbh, $query, 'id', 'unit', @part_ids);
274   }
275   my $q_item = <<SQL;
276     UPDATE delivery_order_items SET
277        delivery_order_id = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
278        sellprice = ?, discount = ?, unit = ?, reqdate = ?, project_id = ?, serialnumber = ?,
279        ordnumber = ?, transdate = ?, cusordnumber = ?,
280        lastcost = ? , price_factor_id = ?, price_factor = (SELECT factor FROM price_factors where id = ?),
281        marge_price_factor = ?, pricegroup_id = ?, active_price_source = ?, active_discount_source = ?
282     WHERE id = ?
283 SQL
284   my $h_item = prepare_query($form, $dbh, $q_item);
285
286   my $q_item_stock = <<SQL;
287     UPDATE delivery_order_items_stock SET
288       delivery_order_item_id = ?, qty = ?,  unit = ?,  warehouse_id = ?,
289       bin_id = ?, chargenumber = ?, bestbefore = ?
290     WHERE id = ?
291 SQL
292   my $h_item_stock = prepare_query($form, $dbh, $q_item_stock);
293
294   my $in_out       = $form->{type} =~ /^sales/ ? 'out' : 'in';
295
296   for my $i (1 .. $form->{rowcount}) {
297     next if (!$form->{"id_$i"});
298
299     if (!$form->{"delivery_order_items_id_$i"}) {
300       # there is no persistent id, therefore create one with all necessary constraints
301       my $q_item_id = qq|SELECT nextval('delivery_order_items_id')|;
302       my $h_item_id = prepare_query($form, $dbh, $q_item_id);
303       do_statement($form, $h_item_id, $q_item_id);
304       $form->{"delivery_order_items_id_$i"}  = $h_item_id->fetchrow_array();
305       $query = qq|INSERT INTO delivery_order_items (id, delivery_order_id, parts_id) VALUES (?, ?, ?)|;
306       do_query($form, $dbh, $query, conv_i($form->{"delivery_order_items_id_$i"}),
307                 conv_i($form->{"id"}), conv_i($form->{"id_$i"}));
308       $h_item_id->finish();
309     }
310     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
311
312     my $item_unit = $part_unit_map{$form->{"id_$i"}};
313
314     my $basefactor = 1;
315     if (defined($all_units->{$item_unit}->{factor}) && (($all_units->{$item_unit}->{factor} * 1) != 0)) {
316       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
317     }
318     my $baseqty = $form->{"qty_$i"} * $basefactor;
319
320     # set values to 0 if nothing entered
321     $form->{"discount_$i"}  = $form->parse_amount($myconfig, $form->{"discount_$i"});
322     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
323     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
324
325     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
326     my $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
327
328     $items_reqdate = ($form->{"reqdate_$i"}) ? $form->{"reqdate_$i"} : undef;
329
330
331     # Get pricegroup_id and save it. Unfortunately the interface
332     # also uses ID "0" for signalling that none is selected, but "0"
333     # must not be stored in the database. Therefore we cannot simply
334     # use conv_i().
335     my $pricegroup_id = $form->{"pricegroup_id_$i"} * 1;
336     $pricegroup_id    = undef if !$pricegroup_id;
337
338     # save detail record in delivery_order_items table
339     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
340                $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}),
341                $form->{"qty_$i"}, $baseqty,
342                $form->{"sellprice_$i"}, $form->{"discount_$i"} / 100,
343                $form->{"unit_$i"}, conv_date($items_reqdate), conv_i($form->{"project_id_$i"}),
344                $form->{"serialnumber_$i"},
345                $form->{"ordnumber_$i"}, conv_date($form->{"transdate_$i"}),
346                $form->{"cusordnumber_$i"},
347                $form->{"lastcost_$i"},
348                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
349                conv_i($form->{"marge_price_factor_$i"}),
350                $pricegroup_id,
351                $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
352                conv_i($form->{"delivery_order_items_id_$i"}));
353     do_statement($form, $h_item, $q_item, @values);
354     push @processed_doi, $form->{"delivery_order_items_id_$i"}; # transaction safe?
355
356     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
357
358     foreach my $sinfo (@{ $stock_info }) {
359       # if we have stock_info, we have to check for persistents entries
360       if (!$sinfo->{"delivery_order_items_stock_id"}) {
361         my $q_item_stock_id = qq|SELECT nextval('id')|;
362         my $h_item_stock_id = prepare_query($form, $dbh, $q_item_stock_id);
363         do_statement($form, $h_item_stock_id, $q_item_stock_id);
364         $sinfo->{"delivery_order_items_stock_id"} = $h_item_stock_id->fetchrow_array();
365         $query = qq|INSERT INTO delivery_order_items_stock (id, delivery_order_item_id, qty, unit, warehouse_id, bin_id)
366                     VALUES (?, ?, ?, ?, ?, ?)|;
367         do_query($form, $dbh, $query, conv_i($sinfo->{"delivery_order_items_stock_id"}),
368                   conv_i($form->{"delivery_order_items_id_$i"}), $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
369                   conv_i($sinfo->{bin_id}));
370        $h_item_stock_id->finish();
371       }
372       @values = ($form->{"delivery_order_items_id_$i"}, $sinfo->{qty}, $sinfo->{unit}, conv_i($sinfo->{warehouse_id}),
373                  conv_i($sinfo->{bin_id}), $sinfo->{chargenumber}, conv_date($sinfo->{bestbefore}),
374                  conv_i($sinfo->{"delivery_order_items_stock_id"}));
375       do_statement($form, $h_item_stock, $q_item_stock, @values);
376       push @processed_dois, $sinfo->{"delivery_order_items_stock_id"};
377     }
378
379     CVar->save_custom_variables(module       => 'IC',
380                                 sub_module   => 'delivery_order_items',
381                                 trans_id     => $form->{"delivery_order_items_id_$i"},
382                                 configs      => $ic_cvar_configs,
383                                 variables    => $form,
384                                 name_prefix  => 'ic_',
385                                 name_postfix => "_$i",
386                                 dbh          => $dbh);
387   }
388
389   # search for orphaned doi
390   $query  = sprintf 'SELECT id FROM delivery_order_items WHERE delivery_order_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_doi;
391   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_doi);
392   my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
393   if (scalar @orphaned_ids) {
394     # clean up delivery_order_items
395     $query  = sprintf 'DELETE FROM delivery_order_items WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
396     do_query($form, $dbh, $query, @orphaned_ids);
397   }
398   # search for orphaned dois
399   $query  = sprintf 'SELECT id FROM delivery_order_items_stock WHERE delivery_order_item_id in
400                       (select id from delivery_order_items where delivery_order_id = ?) AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_dois;
401   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_dois);
402   my @orphaned_dois_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
403   if (scalar @orphaned_dois_ids) {
404     # clean up delivery_order_items_stock
405     $query  = sprintf 'DELETE FROM delivery_order_items_stock WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_dois_ids;
406     do_query($form, $dbh, $query, @orphaned_dois_ids);
407   }
408   $h_item->finish();
409   $h_item_stock->finish();
410
411
412   # reqdate is last items reqdate (?: old behaviour) if not already set
413   $form->{reqdate} ||= $items_reqdate;
414   # save DO record
415   $query =
416     qq|UPDATE delivery_orders SET
417          donumber = ?, ordnumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
418          customer_id = ?, reqdate = ?,
419          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, closed = ?,
420          delivered = ?, department_id = ?, language_id = ?, shipto_id = ?,
421          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?,
422          is_sales = ?, taxzone_id = ?, taxincluded = ?, terms = ?, currency_id = (SELECT id FROM currencies WHERE name = ?),
423          delivery_term_id = ?
424        WHERE id = ?|;
425
426   @values = ($form->{donumber}, $form->{ordnumber},
427              $form->{cusordnumber}, conv_date($form->{transdate}),
428              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
429              conv_date($form->{reqdate}), $form->{shippingpoint}, $form->{shipvia},
430              $form->{notes}, $form->{intnotes},
431              $form->{closed} ? 't' : 'f', $form->{delivered} ? "t" : "f",
432              conv_i($form->{department_id}), conv_i($form->{language_id}), conv_i($form->{shipto_id}),
433              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
434              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
435              $form->{transaction_description},
436              $form->{type} =~ /^sales/ ? 't' : 'f',
437              conv_i($form->{taxzone_id}), $form->{taxincluded} ? 't' : 'f', conv_i($form->{terms}), $form->{currency},
438              conv_i($form->{delivery_term_id}),
439              conv_i($form->{id}));
440   do_query($form, $dbh, $query, @values);
441
442   $form->{name} = $form->{ $form->{vc} };
443   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
444
445   # add shipto
446   if (!$form->{shipto_id}) {
447     $form->add_shipto($dbh, $form->{id}, "DO");
448   }
449
450   # save printed, emailed, queued
451   $form->save_status($dbh);
452
453   # Link this delivery order to the quotations it was created from.
454   RecordLinks->create_links('dbh'        => $dbh,
455                             'mode'       => 'ids',
456                             'from_table' => 'oe',
457                             'from_ids'   => $form->{convert_from_oe_ids},
458                             'to_table'   => 'delivery_orders',
459                             'to_id'      => $form->{id},
460     );
461   delete $form->{convert_from_oe_ids};
462
463   $self->mark_orders_if_delivered('do_id' => $form->{id},
464                                   'type'  => $form->{type} eq 'sales_delivery_order' ? 'sales' : 'purchase',
465                                   'dbh'   => $dbh,);
466
467   my $rc = $dbh->commit();
468
469   $form->{saved_donumber} = $form->{donumber};
470   $form->{saved_ordnumber} = $form->{ordnumber};
471   $form->{saved_cusordnumber} = $form->{cusordnumber};
472
473   Common::webdav_folder($form);
474
475   $main::lxdebug->leave_sub();
476
477   return $rc;
478 }
479
480 sub mark_orders_if_delivered {
481   $main::lxdebug->enter_sub();
482
483   my $self   = shift;
484   my %params = @_;
485
486   Common::check_params(\%params, qw(do_id type));
487
488   my $myconfig = \%main::myconfig;
489   my $form     = $main::form;
490
491   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
492
493   my @links    = RecordLinks->get_links('dbh'        => $dbh,
494                                         'from_table' => 'oe',
495                                         'to_table'   => 'delivery_orders',
496                                         'to_id'      => $params{do_id});
497
498   my $oe_id  = @links ? $links[0]->{from_id} : undef;
499
500   return $main::lxdebug->leave_sub() if (!$oe_id);
501
502   my $all_units = AM->retrieve_all_units();
503
504   my $query     = qq|SELECT oi.parts_id, oi.qty, oi.unit, p.unit AS partunit
505                      FROM orderitems oi
506                      LEFT JOIN parts p ON (oi.parts_id = p.id)
507                      WHERE (oi.trans_id = ?)|;
508   my $sth       = prepare_execute_query($form, $dbh, $query, $oe_id);
509
510   my %shipped   = $self->get_shipped_qty('type'  => $params{type},
511                                          'oe_id' => $oe_id,);
512   my %ordered   = ();
513
514   while (my $ref = $sth->fetchrow_hashref()) {
515     $ref->{baseqty} = $ref->{qty} * $all_units->{$ref->{unit}}->{factor} / $all_units->{$ref->{partunit}}->{factor};
516
517     if ($ordered{$ref->{parts_id}}) {
518       $ordered{$ref->{parts_id}}->{baseqty} += $ref->{baseqty};
519     } else {
520       $ordered{$ref->{parts_id}}             = $ref;
521     }
522   }
523
524   $sth->finish();
525
526   map { $_->{baseqty} = $_->{qty} * $all_units->{$_->{unit}}->{factor} / $all_units->{$_->{partunit}}->{factor} } values %shipped;
527
528   my $delivered = 1;
529   foreach my $part (values %ordered) {
530     if (!$shipped{$part->{parts_id}} || ($shipped{$part->{parts_id}}->{baseqty} < $part->{baseqty})) {
531       $delivered = 0;
532       last;
533     }
534   }
535
536   if ($delivered) {
537     $query = qq|UPDATE oe
538                 SET delivered = TRUE
539                 WHERE id = ?|;
540     do_query($form, $dbh, $query, $oe_id);
541     $dbh->commit() if (!$params{dbh});
542   }
543
544   $main::lxdebug->leave_sub();
545 }
546
547 sub close_orders {
548   $main::lxdebug->enter_sub();
549
550   my $self     = shift;
551   my %params   = @_;
552
553   Common::check_params(\%params, qw(ids));
554
555   if (('ARRAY' ne ref $params{ids}) || !scalar @{ $params{ids} }) {
556     $main::lxdebug->leave_sub();
557     return;
558   }
559
560   my $myconfig = \%main::myconfig;
561   my $form     = $main::form;
562
563   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
564
565   my $query    = qq|UPDATE delivery_orders SET closed = TRUE WHERE id IN (| . join(', ', ('?') x scalar(@{ $params{ids} })) . qq|)|;
566
567   do_query($form, $dbh, $query, map { conv_i($_) } @{ $params{ids} });
568
569   $dbh->commit() unless ($params{dbh});
570
571   $main::lxdebug->leave_sub();
572 }
573
574 sub delete {
575   $main::lxdebug->enter_sub();
576
577   my ($self)   = @_;
578
579   my $myconfig = \%main::myconfig;
580   my $form     = $main::form;
581   my $spool    = $::lx_office_conf{paths}->{spool};
582
583   my $rc = SL::DB::Order->new->db->with_transaction(sub {
584     my @spoolfiles = grep { $_ } map { $_->spoolfile } @{ SL::DB::Manager::Status->get_all(where => [ trans_id => $form->{id} ]) };
585
586     SL::DB::DeliveryOrder->new(id => $form->{id})->delete;
587
588     my $spool = $::lx_office_conf{paths}->{spool};
589     unlink map { "$spool/$_" } @spoolfiles if $spool;
590
591     1;
592   });
593
594   $main::lxdebug->leave_sub();
595
596   return $rc;
597 }
598
599 sub retrieve {
600   $main::lxdebug->enter_sub();
601
602   my $self     = shift;
603   my %params   = @_;
604
605   my $myconfig = \%main::myconfig;
606   my $form     = $main::form;
607
608   # connect to database
609   my $dbh = $form->get_standard_dbh($myconfig);
610
611   my ($query, $query_add, @values, $sth, $ref);
612
613   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
614                                           dbh    => $dbh);
615
616   my $vc   = $params{vc} eq 'customer' ? 'customer' : 'vendor';
617
618   my $mode = !$params{ids} ? 'default' : ref $params{ids} eq 'ARRAY' ? 'multi' : 'single';
619
620   if ($mode eq 'default') {
621     $ref = selectfirst_hashref_query($form, $dbh, qq|SELECT current_date AS transdate|);
622     map { $form->{$_} = $ref->{$_} } keys %$ref;
623
624     # if reqdate is not set from oe-workflow, set it to transdate (which is current date)
625     $form->{reqdate} ||= $form->{transdate};
626
627     # get last name used
628     $form->lastname_used($dbh, $myconfig, $vc) unless $form->{"${vc}_id"};
629
630     $main::lxdebug->leave_sub();
631
632     return 1;
633   }
634
635   my @do_ids              = map { conv_i($_) } ($mode eq 'multi' ? @{ $params{ids} } : ($params{ids}));
636   my $do_ids_placeholders = join(', ', ('?') x scalar(@do_ids));
637
638   # retrieve order for single id
639   # NOTE: this query is intended to fetch all information only ONCE.
640   # so if any of these infos is important (or even different) for any item,
641   # it will be killed out and then has to be fetched from the item scope query further down
642   $query =
643     qq|SELECT dord.cp_id, dord.donumber, dord.ordnumber, dord.transdate, dord.reqdate,
644          dord.shippingpoint, dord.shipvia, dord.notes, dord.intnotes,
645          e.name AS employee, dord.employee_id, dord.salesman_id,
646          dord.${vc}_id, cv.name AS ${vc},
647          dord.closed, dord.reqdate, dord.department_id, dord.cusordnumber,
648          d.description AS department, dord.language_id,
649          dord.shipto_id,
650          dord.globalproject_id, dord.delivered, dord.transaction_description,
651          dord.taxzone_id, dord.taxincluded, dord.terms, (SELECT cu.name FROM currencies cu WHERE cu.id=dord.currency_id) AS currency,
652          dord.delivery_term_id
653        FROM delivery_orders dord
654        JOIN ${vc} cv ON (dord.${vc}_id = cv.id)
655        LEFT JOIN employee e ON (dord.employee_id = e.id)
656        LEFT JOIN department d ON (dord.department_id = d.id)
657        WHERE dord.id IN ($do_ids_placeholders)|;
658   $sth = prepare_execute_query($form, $dbh, $query, @do_ids);
659
660   delete $form->{"${vc}_id"};
661   my $pos = 0;
662   $form->{ordnumber_array} = ' ';
663   $form->{cusordnumber_array} = ' ';
664   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
665     if ($form->{"${vc}_id"} && ($ref->{"${vc}_id"} != $form->{"${vc}_id"})) {
666       $sth->finish();
667       $main::lxdebug->leave_sub();
668
669       return 0;
670     }
671
672     map { $form->{$_} = $ref->{$_} } keys %$ref if ($ref);
673     $form->{donumber_array} .= $form->{donumber} . ' ';
674     $pos = index($form->{ordnumber_array},' ' . $form->{ordnumber} . ' ');
675     if ($pos == -1) {
676       $form->{ordnumber_array} .= $form->{ordnumber} . ' ';
677     }
678     $pos = index($form->{cusordnumber_array},' ' . $form->{cusordnumber} . ' ');
679     if ($pos == -1) {
680       $form->{cusordnumber_array} .= $form->{cusordnumber} . ' ';
681     }
682   }
683   $sth->finish();
684
685   $form->{donumber_array} =~ s/\s*$//g;
686   $form->{ordnumber_array} =~ s/ //;
687   $form->{ordnumber_array} =~ s/\s*$//g;
688   $form->{cusordnumber_array} =~ s/ //;
689   $form->{cusordnumber_array} =~ s/\s*$//g;
690
691   $form->{saved_donumber} = $form->{donumber};
692   $form->{saved_ordnumber} = $form->{ordnumber};
693   $form->{saved_cusordnumber} = $form->{cusordnumber};
694
695   # if not given, fill transdate with current_date
696   $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
697
698   if ($mode eq 'single') {
699     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'DO'|;
700     $sth   = prepare_execute_query($form, $dbh, $query, $form->{id});
701
702     $ref   = $sth->fetchrow_hashref("NAME_lc");
703     delete $ref->{id};
704     map { $form->{$_} = $ref->{$_} } keys %$ref;
705     $sth->finish();
706
707     # get printed, emailed and queued
708     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname FROM status s WHERE s.trans_id = ?|;
709     $sth   = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
710
711     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
712       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
713       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
714       $form->{queued}  .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
715     }
716     $sth->finish();
717     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
718
719   } else {
720     delete $form->{id};
721   }
722
723   # retrieve individual items
724   # this query looks up all information about the items
725   # stuff different from the whole will not be overwritten, but saved with a suffix.
726   $query =
727     qq|SELECT doi.id AS delivery_order_items_id,
728          p.partnumber, p.assembly, p.listprice, doi.description, doi.qty,
729          doi.sellprice, doi.parts_id AS id, doi.unit, doi.discount, p.notes AS partnotes,
730          doi.reqdate, doi.project_id, doi.serialnumber, doi.lastcost,
731          doi.ordnumber, doi.transdate, doi.cusordnumber, doi.longdescription,
732          doi.price_factor_id, doi.price_factor, doi.marge_price_factor, doi.pricegroup_id,
733          doi.active_price_source, doi.active_discount_source,
734          pr.projectnumber, dord.transdate AS dord_transdate, dord.donumber,
735          pg.partsgroup
736        FROM delivery_order_items doi
737        JOIN parts p ON (doi.parts_id = p.id)
738        JOIN delivery_orders dord ON (doi.delivery_order_id = dord.id)
739        LEFT JOIN project pr ON (doi.project_id = pr.id)
740        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
741        WHERE doi.delivery_order_id IN ($do_ids_placeholders)
742        ORDER BY doi.oid|;
743
744   $form->{form_details} = selectall_hashref_query($form, $dbh, $query, @do_ids);
745
746   # Retrieve custom variables.
747   foreach my $doi (@{ $form->{form_details} }) {
748     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
749                                            module     => 'IC',
750                                            sub_module => 'delivery_order_items',
751                                            trans_id   => $doi->{delivery_order_items_id},
752                                           );
753     map { $doi->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
754   }
755
756   if ($mode eq 'single') {
757     my $in_out = $form->{type} =~ /^sales/ ? 'out' : 'in';
758
759     $query =
760       qq|SELECT id as delivery_order_items_stock_id, qty, unit, bin_id,
761                 warehouse_id, chargenumber, bestbefore
762          FROM delivery_order_items_stock
763          WHERE delivery_order_item_id = ?|;
764     my $sth = prepare_query($form, $dbh, $query);
765
766     foreach my $doi (@{ $form->{form_details} }) {
767       do_statement($form, $sth, $query, conv_i($doi->{delivery_order_items_id}));
768       my $requests = [];
769       while (my $ref = $sth->fetchrow_hashref()) {
770         push @{ $requests }, $ref;
771       }
772
773       $doi->{"stock_${in_out}"} = YAML::Dump($requests);
774     }
775
776     $sth->finish();
777   }
778
779   Common::webdav_folder($form);
780
781   $main::lxdebug->leave_sub();
782
783   return 1;
784 }
785
786 sub order_details {
787   $main::lxdebug->enter_sub();
788
789   my ($self, $myconfig, $form) = @_;
790
791   # connect to database
792   my $dbh = $form->get_standard_dbh($myconfig);
793   my $query;
794   my @values = ();
795   my $sth;
796   my $item;
797   my $i;
798   my @partsgroup = ();
799   my $partsgroup;
800   my $position = 0;
801   my $subtotal_header = 0;
802   my $subposition = 0;
803   my $si_position = 0;
804
805   my (@project_ids);
806
807   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
808
809   # sort items by partsgroup
810   for $i (1 .. $form->{rowcount}) {
811     $partsgroup = "";
812     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
813       $partsgroup = $form->{"partsgroup_$i"};
814     }
815     push @partsgroup, [$i, $partsgroup];
816     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
817   }
818
819   my $projects = [];
820   my %projects_by_id;
821   if (@project_ids) {
822     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
823     %projects_by_id = map { $_->id => $_ } @$projects;
824   }
825
826   if ($projects_by_id{$form->{"globalproject_id"}}) {
827     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
828     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
829
830     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
831       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
832     }
833   }
834
835   my $q_pg     = qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
836                     FROM assembly a
837                     JOIN parts p ON (a.parts_id = p.id)
838                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
839                     WHERE a.bom = '1'
840                       AND a.id = ?|;
841   my $h_pg     = prepare_query($form, $dbh, $q_pg);
842
843   my $q_bin_wh = qq|SELECT (SELECT description FROM bin       WHERE id = ?) AS bin,
844                            (SELECT description FROM warehouse WHERE id = ?) AS warehouse|;
845   my $h_bin_wh = prepare_query($form, $dbh, $q_bin_wh);
846
847   my $in_out   = $form->{type} =~ /^sales/ ? 'out' : 'in';
848
849   my $num_si   = 0;
850
851   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
852   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
853
854   $form->{TEMPLATE_ARRAYS} = { };
855   IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
856
857   my @arrays =
858     qw(runningnumber number description longdescription qty unit
859        partnotes serialnumber reqdate projectnumber projectdescription
860        weight lineweight
861        si_runningnumber si_number si_description
862        si_warehouse si_bin si_chargenumber si_bestbefore
863        si_qty si_qty_nofmt si_unit);
864
865   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays);
866
867   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
868   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
869
870   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
871   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
872
873   my $totalweight = 0;
874   my $sameitem = "";
875   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
876     $i = $item->[0];
877
878     next if (!$form->{"id_$i"});
879
880     if ($item->[1] ne $sameitem) {
881       push(@{ $form->{description} }, qq|$item->[1]|);
882       $sameitem = $item->[1];
883
884       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
885     }
886
887     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
888
889     # add number, description and qty to $form->{number}, ....
890     if ($form->{"subtotal_$i"} && !$subtotal_header) {
891       $subtotal_header = $i;
892       $position = int($position);
893       $subposition = 0;
894       $position++;
895     } elsif ($subtotal_header) {
896       $subposition += 1;
897       $position = int($position);
898       $position = $position.".".$subposition;
899     } else {
900       $position = int($position);
901       $position++;
902     }
903
904     $si_position++;
905
906     my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
907     my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
908
909     push @{ $form->{TEMPLATE_ARRAYS}{runningnumber} },   $position;
910     push @{ $form->{TEMPLATE_ARRAYS}{number} },          $form->{"partnumber_$i"};
911     push @{ $form->{TEMPLATE_ARRAYS}{description} },     $form->{"description_$i"};
912     push @{ $form->{TEMPLATE_ARRAYS}{longdescription} }, $form->{"longdescription_$i"};
913     push @{ $form->{TEMPLATE_ARRAYS}{qty} },             $form->format_amount($myconfig, $form->{"qty_$i"});
914     push @{ $form->{TEMPLATE_ARRAYS}{qty_nofmt} },       $form->{"qty_$i"};
915     push @{ $form->{TEMPLATE_ARRAYS}{unit} },            $form->{"unit_$i"};
916     push @{ $form->{TEMPLATE_ARRAYS}{partnotes} },       $form->{"partnotes_$i"};
917     push @{ $form->{TEMPLATE_ARRAYS}{serialnumber} },    $form->{"serialnumber_$i"};
918     push @{ $form->{TEMPLATE_ARRAYS}{reqdate} },         $form->{"reqdate_$i"};
919     push @{ $form->{TEMPLATE_ARRAYS}{projectnumber} },   $project->projectnumber;
920     push @{ $form->{TEMPLATE_ARRAYS}{projectdescription} }, $project->description;
921
922     if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
923       $subtotal_header     = 0;
924     }
925
926     my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
927     $totalweight += $lineweight;
928     push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
929     push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
930     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
931     push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
932
933     my $stock_info = DO->unpack_stock_information('packed' => $form->{"stock_${in_out}_$i"});
934
935     foreach my $si (@{ $stock_info }) {
936       $num_si++;
937
938       do_statement($form, $h_bin_wh, $q_bin_wh, conv_i($si->{bin_id}), conv_i($si->{warehouse_id}));
939       my $bin_wh = $h_bin_wh->fetchrow_hashref();
940
941       push @{ $form->{TEMPLATE_ARRAYS}{si_runningnumber}[$si_position-1] }, $num_si;
942       push @{ $form->{TEMPLATE_ARRAYS}{si_number}[$si_position-1] },        $form->{"partnumber_$i"};
943       push @{ $form->{TEMPLATE_ARRAYS}{si_description}[$si_position-1] },   $form->{"description_$i"};
944       push @{ $form->{TEMPLATE_ARRAYS}{si_warehouse}[$si_position-1] },     $bin_wh->{warehouse};
945       push @{ $form->{TEMPLATE_ARRAYS}{si_bin}[$si_position-1] },           $bin_wh->{bin};
946       push @{ $form->{TEMPLATE_ARRAYS}{si_chargenumber}[$si_position-1] },  $si->{chargenumber};
947       push @{ $form->{TEMPLATE_ARRAYS}{si_bestbefore}[$si_position-1] },    $si->{bestbefore};
948       push @{ $form->{TEMPLATE_ARRAYS}{si_qty}[$si_position-1] },           $form->format_amount($myconfig, $si->{qty} * 1);
949       push @{ $form->{TEMPLATE_ARRAYS}{si_qty_nofmt}[$si_position-1] },     $si->{qty} * 1;
950       push @{ $form->{TEMPLATE_ARRAYS}{si_unit}[$si_position-1] },          $si->{unit};
951     }
952
953     if ($form->{"assembly_$i"}) {
954       $sameitem = "";
955
956       # get parts and push them onto the stack
957       my $sortorder = "";
958       if ($form->{groupitems}) {
959         $sortorder =
960           qq|ORDER BY pg.partsgroup, a.oid|;
961       } else {
962         $sortorder = qq|ORDER BY a.oid|;
963       }
964
965       do_statement($form, $h_pg, $q_pg, conv_i($form->{"id_$i"}));
966
967       while (my $ref = $h_pg->fetchrow_hashref("NAME_lc")) {
968         if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
969           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} @arrays));
970           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
971           $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
972           push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
973           $si_position++;
974         }
975
976         push(@{ $form->{TEMPLATE_ARRAYS}->{"description"} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}) . qq| -- $ref->{partnumber}, $ref->{description}|);
977         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" && $_ !~ /^si_/} @arrays));
978         map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, []) } grep({ $_ =~ /^si_/} @arrays));
979         $si_position++;
980       }
981     }
982
983     push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
984       CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
985         for @{ $ic_cvar_configs };
986
987     push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
988   }
989
990   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
991   $form->{totalweight_nofmt} = $totalweight;
992   my $defaults = AM->get_defaults();
993   $form->{weightunit}        = $defaults->{weightunit};
994
995   $h_pg->finish();
996   $h_bin_wh->finish();
997
998   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
999   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
1000
1001   $form->{username} = $myconfig->{name};
1002
1003   $main::lxdebug->leave_sub();
1004 }
1005
1006 sub project_description {
1007   $main::lxdebug->enter_sub();
1008
1009   my ($self, $dbh, $id) = @_;
1010
1011   my $form     =  $main::form;
1012
1013   my $query = qq|SELECT description FROM project WHERE id = ?|;
1014   my ($value) = selectrow_query($form, $dbh, $query, $id);
1015
1016   $main::lxdebug->leave_sub();
1017
1018   return $value;
1019 }
1020
1021 sub unpack_stock_information {
1022   $main::lxdebug->enter_sub();
1023
1024   my $self   = shift;
1025   my %params = @_;
1026
1027   Common::check_params_x(\%params, qw(packed));
1028
1029   my $unpacked;
1030
1031   eval { $unpacked = $params{packed} ? YAML::Load($params{packed}) : []; };
1032
1033   $unpacked = [] if (!$unpacked || ('ARRAY' ne ref $unpacked));
1034
1035   foreach my $entry (@{ $unpacked }) {
1036     next if ('HASH' eq ref $entry);
1037     $unpacked = [];
1038     last;
1039   }
1040
1041   $main::lxdebug->leave_sub();
1042
1043   return $unpacked;
1044 }
1045
1046 sub get_item_availability {
1047   $::lxdebug->enter_sub;
1048
1049   my $self     = shift;
1050   my %params   = @_;
1051
1052   Common::check_params(\%params, qw(parts_id));
1053
1054   my @parts_ids = 'ARRAY' eq ref $params{parts_id} ? @{ $params{parts_id} } : ($params{parts_id});
1055
1056   my $query     =
1057     qq|SELECT i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, SUM(qty) AS qty, i.parts_id,
1058          w.description AS warehousedescription,
1059          b.description AS bindescription
1060        FROM inventory i
1061        LEFT JOIN warehouse w ON (i.warehouse_id = w.id)
1062        LEFT JOIN bin b       ON (i.bin_id       = b.id)
1063        WHERE (i.parts_id IN (| . join(', ', ('?') x scalar(@parts_ids)) . qq|))
1064        GROUP BY i.warehouse_id, i.bin_id, i.chargenumber, i.bestbefore, i.parts_id, w.description, b.description
1065        HAVING SUM(qty) > 0
1066        ORDER BY LOWER(w.description), LOWER(b.description), LOWER(i.chargenumber), i.bestbefore
1067 |;
1068   my $contents = selectall_hashref_query($::form, $::form->get_standard_dbh, $query, @parts_ids);
1069
1070   $::lxdebug->leave_sub;
1071
1072   return @{ $contents };
1073 }
1074
1075
1076 sub check_stock_availability {
1077   $main::lxdebug->enter_sub();
1078
1079   my $self     = shift;
1080   my %params   = @_;
1081
1082   Common::check_params(\%params, qw(requests parts_id));
1083
1084   my $myconfig    = \%main::myconfig;
1085   my $form        =  $main::form;
1086
1087   my $dbh         = $form->get_standard_dbh($myconfig);
1088
1089   my $units       = AM->retrieve_units($myconfig, $form);
1090
1091   my ($partunit)  = selectrow_query($form, $dbh, qq|SELECT unit FROM parts WHERE id = ?|, conv_i($params{parts_id}));
1092   my $unit_factor = $units->{$partunit}->{factor} || 1;
1093
1094   my @contents    = $self->get_item_availability(%params);
1095
1096   my @errors;
1097
1098   foreach my $sinfo (@{ $params{requests} }) {
1099     my $found = 0;
1100
1101     foreach my $row (@contents) {
1102       next if (($row->{bin_id}       != $sinfo->{bin_id}) ||
1103                ($row->{warehouse_id} != $sinfo->{warehouse_id}) ||
1104                ($row->{chargenumber} ne $sinfo->{chargenumber}) ||
1105                ($row->{bestbefore}   ne $sinfo->{bestbefore}));
1106
1107       $found       = 1;
1108
1109       my $base_qty = $sinfo->{qty} * $units->{$sinfo->{unit}}->{factor} / $unit_factor;
1110
1111       if ($base_qty > $row->{qty}) {
1112         $sinfo->{error} = 1;
1113         push @errors, $sinfo;
1114
1115         last;
1116       }
1117     }
1118
1119     push @errors, $sinfo if (!$found);
1120   }
1121
1122   $main::lxdebug->leave_sub();
1123
1124   return @errors;
1125 }
1126
1127 sub transfer_in_out {
1128   $main::lxdebug->enter_sub();
1129
1130   my $self     = shift;
1131   my %params   = @_;
1132
1133   Common::check_params(\%params, qw(direction requests));
1134
1135   if (!@{ $params{requests} }) {
1136     $main::lxdebug->leave_sub();
1137     return;
1138   }
1139
1140   my $myconfig = \%main::myconfig;
1141   my $form     = $main::form;
1142
1143   my $prefix   = $params{direction} eq 'in' ? 'dst' : 'src';
1144
1145   my @transfers;
1146
1147   foreach my $request (@{ $params{requests} }) {
1148     push @transfers, {
1149       'parts_id'               => $request->{parts_id},
1150       "${prefix}_warehouse_id" => $request->{warehouse_id},
1151       "${prefix}_bin_id"       => $request->{bin_id},
1152       'chargenumber'           => $request->{chargenumber},
1153       'bestbefore'             => $request->{bestbefore},
1154       'qty'                    => $request->{qty},
1155       'unit'                   => $request->{unit},
1156       'oe_id'                  => $form->{id},
1157       'shippingdate'           => 'current_date',
1158       'transfer_type'          => $params{direction} eq 'in' ? 'stock' : 'shipped',
1159       'project_id'             => $request->{project_id},
1160     };
1161   }
1162
1163   WH->transfer(@transfers);
1164
1165   $main::lxdebug->leave_sub();
1166 }
1167
1168 sub get_shipped_qty {
1169   $main::lxdebug->enter_sub();
1170
1171   my $self     = shift;
1172   my %params   = @_;
1173
1174   Common::check_params(\%params, qw(type oe_id));
1175
1176   my $myconfig = \%main::myconfig;
1177   my $form     = $main::form;
1178
1179   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1180
1181   my @links    = RecordLinks->get_links('dbh'        => $dbh,
1182                                         'from_table' => 'oe',
1183                                         'from_id'    => $params{oe_id},
1184                                         'to_table'   => 'delivery_orders');
1185   my @values   = map { $_->{to_id} } @links;
1186
1187   if (!scalar @values) {
1188     $main::lxdebug->leave_sub();
1189     return ();
1190   }
1191
1192   my $query =
1193     qq|SELECT doi.parts_id, doi.qty, doi.unit, p.unit AS partunit
1194        FROM delivery_order_items doi
1195        LEFT JOIN delivery_orders o ON (doi.delivery_order_id = o.id)
1196        LEFT JOIN parts p ON (doi.parts_id = p.id)
1197        WHERE o.id IN (| . join(', ', ('?') x scalar @values) . qq|)|;
1198
1199   my %ship      = ();
1200   my $entries   = selectall_hashref_query($form, $dbh, $query, @values);
1201   my $all_units = AM->retrieve_all_units();
1202
1203   foreach my $entry (@{ $entries }) {
1204     $entry->{qty} *= AM->convert_unit($entry->{unit}, $entry->{partunit}, $all_units);
1205
1206     if (!$ship{$entry->{parts_id}}) {
1207       $ship{$entry->{parts_id}} = $entry;
1208     } else {
1209       $ship{$entry->{parts_id}}->{qty} += $entry->{qty};
1210     }
1211   }
1212
1213   $main::lxdebug->leave_sub();
1214
1215   return %ship;
1216 }
1217
1218 sub is_marked_as_delivered {
1219   $main::lxdebug->enter_sub();
1220
1221   my $self     = shift;
1222   my %params   = @_;
1223
1224   Common::check_params(\%params, qw(id));
1225
1226   my $myconfig    = \%main::myconfig;
1227   my $form        = $main::form;
1228
1229   my $dbh         = $params{dbh} || $form->get_standard_dbh($myconfig);
1230
1231   my ($delivered) = selectfirst_array_query($form, $dbh, qq|SELECT delivered FROM delivery_orders WHERE id = ?|, conv_i($params{id}));
1232
1233   $main::lxdebug->leave_sub();
1234
1235   return $delivered ? 1 : 0;
1236 }
1237
1238
1239 1;