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