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