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