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