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