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