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