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