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