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